最近專案中需要使用使用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"); }
相關推薦:
# #########PHPExcel如何實現合併與分割單元格######以上是tp5中phpexcel生成表格實例分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!