官网http://phpexcel.codeplex.com/下载最新PHPExcel放到tp框架的核心目录ThinkPHP里面的Vendor下
1 public function test(){ 2 $xlsName = "用户"; 3 4 //注意 数组第一个字段必须是小写 数组第二个(列标题)根据你的情况填写 5 $xlsCell = array( 6 array('字段1','账号序列'), 7 array('字段2','登录账户'), 8 array('字段3','账户昵称'), 9 array('字段4','真实姓名'), 10 array('字段5','身份') 11 ); 12 $xlsModel = M('表名'); 13 $xlsData = $xlsModel->Field('字段1,字段2,字段3,字段4,字段5')->select(); 14 exportExcel($xlsName,$xlsCell,$xlsData); 15 }
建议将这个方法放在common里面的function里面,方便调用
1 //导出excel $expTitle:文件名称 $expCellName:表头标题 $expTableData:数据源 2 public function exportExcel($expTitle,$expCellName,$expTableData){ 3 vendor("phpexcel.Classes.PHPExcel"); 4 $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称 5 $fileName = $xlsTitle;//or $xlsTitle 文件名称可根据自己情况设定 6 $cellNum = count($expCellName); 7 $dataNum = count($expTableData); 8 9 $objPHPExcel = new PHPExcel(); 10 $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ'); 11 12 $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格 13 $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.' 导出时间:'.date('Y-m-d H:i:s')); 14 for($i=0;$i<$cellNum;$i++){ 15 $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]); 16 } 17 // Miscellaneous glyphs, UTF-8 18 for($i=0;$i<$dataNum;$i++){ 19 for($j=0;$j<$cellNum;$j++){ 20 $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]); 21 } 22 } 23 24 header('pragma:public'); 25 header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"'); 26 header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印 27 $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); 28 $objWriter->save('php://output'); 29 exit; 30 }