官网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 $this->exportExcel($xlsName,$xlsCell,$xlsData); 15 }
//导出excel $expTitle:文件名称 $expCellName:表头标题 $expTableData:数据源
1 public function exportExcel($expTitle,$expCellName,$expTableData){ 2 vendor("phpexcel.Classes.PHPExcel"); 3 $xlsTitle = iconv(‘utf-8‘, ‘gb2312‘, $expTitle);//文件名称 4 $fileName = $xlsTitle;//or $xlsTitle 文件名称可根据自己情况设定 5 $cellNum = count($expCellName); 6 $dataNum = count($expTableData); 7 8 $objPHPExcel = new \PHPExcel(); 9 $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‘); 10 11 $objPHPExcel->getActiveSheet(0)->mergeCells(‘A1:‘.$cellName[$cellNum-1].‘1‘);//合并单元格 12 $objPHPExcel->setActiveSheetIndex(0)->setCellValue(‘A1‘, $expTitle.‘ 导出时间:‘.date(‘Y-m-d H:i:s‘)); 13 for($i=0;$i<$cellNum;$i++){ 14 $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].‘2‘, $expCellName[$i][1]); 15 } 16 // Miscellaneous glyphs, UTF-8 17 for($i=0;$i<$dataNum;$i++){ 18 for($j=0;$j<$cellNum;$j++){ 19 $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]); 20 } 21 } 22 23 header(‘pragma:public‘); 24 header(‘Content-type:application/vnd.ms-excel;charset=utf-8;name="‘.$xlsTitle.‘.xls"‘); 25 header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印 26 $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel5‘); 27 $objWriter->save(‘php://output‘); 28 exit; 29 }
时间: 2024-11-01 13:46:50