tp5中phpexcel生成表格实例分享
程序员文章站
2022-05-13 13:30:23
...
最近项目中需要使用使用phpexcel生成表格,但是在由网页导出excel时,文件的后缀总是会带上html。后来调试了半天发现,需要在header头输出之前使用ob_end_clean( )去清除php缓冲区中的内容。因为在herder头输出之前,php是不能有任何输出的,哪怕是一个空格,一旦有了输出,你设置的php header头就无效了,因为此时的header头信息早已经固定。
输出excle时出现乱码的情况也是用这种方式解决。
/** * 下载excel表格 */ public function down_excel() { $params = $_GET; $filename = $params['cname'] . '收银明细列表' . date('Y-m-d'); $objPHPExcel = new \PHPExcel(); //设置表头信息 $letter = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'); $excel_column = array( 'id' => "订单号", 'dt' => "交易时间", 'money' => "金额", 'status' => "交易状态", 'pay_type' => "支付渠道", 'device' => "终端号", 'operator' => "收银员", 'pay_id' => "渠道流水号", 'client_name' => "商户名称", 'pay_scense' => "支付场景", 'operate_fee' => "手续费", 'no' => "小票单号", ); $new_letter = []; $new_excel_column = []; foreach ($params['act_name'] as $k => $d) { $new_letter[$d] = $letter[$k]; $new_excel_column[$d] = $excel_column[$d]; } foreach ($new_excel_column as $k => $d) { //设置行宽自动调整 $objPHPExcel->getActiveSheet()->getColumnDimension($new_letter[$k])->setWidth(12); $objPHPExcel->getActiveSheet()->setCellValue($new_letter[$k] . '1', $d); } //填充表格信息 $data['rows'] = []; foreach ($params['down_class'] as $item) { switch ($item) { case 'pay_success': $params['dm_status'] = 2; break; case 'refund_success': $params['dm_status'] = 4; break; case 'pay_fail': $params['dm_status'] = 3; break; case 'pay_undefined': $params['dm_status'] = 5; break; } $ret = $this->getData($params); $data['rows'] = array_merge($data['rows'], $ret['rows']); } $total = 0; if (!empty($data['rows'])) { foreach ($data['rows'] as $k => $d) { $i = $k + 2; foreach ($new_letter as $key => $item) { //填充数据 $objPHPExcel->getActiveSheet()->setCellValue($item . $i, strip_tags($d[$key])); } $total += strip_tags($d['money']); } } $index = count($data['rows']) + 2; $objPHPExcel->getActiveSheet()->mergeCells("A{$index}:B{$index}"); $objPHPExcel->getActiveSheet()->setCellValue('A' . $index, '合计'); $objPHPExcel->getActiveSheet()->setCellValue('C' . $index, $total); //保存表格版本格式 $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,"Excel2007"); //下载表格 ob_end_clean(); //关闭缓冲区之后再输出header头,在header设置之前,可能某个地方有了输出,导致Content-Type的类型为text/html,所以输出的表格后缀才会是html header('Content-Type: application/octet-stream'); header("Content-Disposition: attachment; filename=\"{$filename}.xlsx\""); $objWriter->save("php://output"); }
相关推荐:
以上就是tp5中phpexcel生成表格实例分享的详细内容,更多请关注其它相关文章!
上一篇: Catalyst4006交换机的配置实例
下一篇: 子流程---5