去PHPExcel官网下载,然后将解压后的classes里面的内容全部放到Thinkphp框架里的Library/Org/Util下面,并将PHPExcel.php修改为PHPExcel.class.php;
然后在你需要导出的地方添加如下代码:
function exportExcel()
{
import('Org.Util.PHPExcel');
import('org.Util.PHPExcel.Reader.Excel2007');
$objPHPExcel = new \PHPExcel(); //这里要注意‘\’ 要有这个。因为版本是3.1.2了。
$objDrawing = new \PHPExcel_Worksheet_Drawing();
$objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel); //设置保存版本格式
//接下来就是写数据到表格里面去
$user=M('user','xiaowei_','DB_CONFIG2');
$list=$user->field('id,name,emp_no,password,pic')->order('id desc')->select();
foreach ($list as $key => $value)
{
$i=$key+1;//表格是从1开始的
$objPHPExcel->getActiveSheet()->setCellValue('A'.$i, $value['name']);//这里是设置A1单元格的内容
$objPHPExcel->getActiveSheet()->setCellValue('B'.$i, $value['id']);////这里是设置B1单元格的内容
$objPHPExcel->getActiveSheet()->setCellValue('C'.$i, $value['emp_no']);
$objPHPExcel->getActiveSheet()->setCellValue('D'.$i, $value['password']);
//以此类推,可以设置C D E F G看你需要了。
}
//接下来当然是下载这个表格了,在浏览器输出就好了
header("Pragma: public");
header("Expires: 0");
header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
header("Content-Type:application/force-download");
header("Content-Type:application/vnd.ms-execl");
header("Content-Type:application/octet-stream");
header("Content-Type:application/download");;
header('Content-Disposition:attachment;filename=test.xls');
header("Content-Transfer-Encoding:binary");
$objWriter->save('test.xls');
$objWriter->save('php://output');
}
上面只是完成了基本的流程,我们还可以设置很多东西
//设置某个单元格的值
$objPHPExcel->getActiveSheet()->setCellValue('A18', '合并');
//合并单元格
$objPHPExcel->getActiveSheet()->mergeCells('B1:E2');
//设置宽width
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
//设置font
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setName('Candara');
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setSize(20);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true); //加粗
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setUnderline(\PHPExcel_Style_Font::UNDERLINE_SINGLE);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->getColor()->setARGB(\PHPExcel_Style_Color::COLOR_WHITE);
$objPHPExcel->getActiveSheet()->getStyle('E1')->getFont()->getColor()->setARGB(\PHPExcel_Style_Color::COLOR_WHITE);
$objPHPExcel->getActiveSheet()->getStyle('D13')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('E13')->getFont()->setBold(true);