在实际开发中,有很多场景是需要导出Excel表格的,比如后台的统计数据,客户希望能导出为表格的形式,今天介绍一下TP5框架内实现Excel表格的导出功能,首先下载phpexcel.zip,解压后放到vendor第三方类库目录下,直接用函数vendor()引入就可以啦,直接贴代码:
public function pushExcelAll(Request $request) { vendor('phpexcel.PHPExcel'); //引入核心库文件 vendor('phpexcel.PHPExcel.Writer.Excel2007'); //引入excel2007操作类 vendor('phpexcel.PHPExcel.IOFactory'); $param = $request->param(); $id = $param['id']; //要导出的数据id $name = isset($param['name']) ? $param['name'] : 'ExampleMemb'; //要导出的Excel表名 $data = MeetingMembs::query("select platform,ticketType,avatar,realName,phone,company,job,email,ticketRemark,seatCode,id from h_meetingmembs where id = $id"); //从数据库中查到数据 error_reporting(E_ALL); $objPHPExcel = new \PHPExcel(); $letter = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'); //表头数组 $tableheader = array('购票平台', '票类', '头像', '姓名', '手机号码', '单位名称', '职位', '邮箱', '备注', '坐席', '报名号'); //填充表头信息 for ($i = 0; $i < count($tableheader); $i++) { $objPHPExcel->getActiveSheet()->setCellValue("$letter[$i]1", "$tableheader[$i]"); } /*以下就是对处理Excel里的数据,横着取数据,主要是这一步,其他基本都不要改*/ foreach ($data as $k => $v) { $num = $k + 1 + 1; $objPHPExcel->setActiveSheetIndex(0) //Excel的第A列,uid是你查出数组的键值,下面以此类推 ->setCellValue('A' . $num, $v['platform'])//platform ->setCellValue('B' . $num, $v['ticketType'])//ticketType ->setCellValue('C' . $num, $v['avatar'])//avatar ->setCellValue('D' . $num, $v['realName'])//realName ->setCellValue('E' . $num, $v['phone'])//phone ->setCellValue('F' . $num, $v['company'])//company ->setCellValue('G' . $num, $v['job'])//job ->setCellValue('H' . $num, $v['email'])//email ->setCellValue('I' . $num, $v['ticketRemark'])//ticketRemark ->setCellValue('J' . $num, $v['seatCode'])//seatCode ->setCellValue('K' . $num, $v['id']);//id } $objPHPExcel->getActiveSheet()->setTitle('signMemb'); $objPHPExcel->setActiveSheetIndex(0); header('Content-Type: application/vnd.ms-excel;charset=UTF-8"'); header('Content-Disposition: attachment;filename="' . $name . '.xls"'); header('Cache-Control: max-age=0'); $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); exit; }
相对应的修改几个值,$id,$name,$data,$letter,$tableheader和foreach循环中的$v的属性名,不出意外的话到此你就已经搞定了导出功能。
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。