應用phpexcel導出excel文件后打不開的問題解決方法


應用phpexcel導出excel文件后打不開,提示“文件格式或文件擴展名無效,請確定文件未損壞,並且文件擴展名與文件的格式匹配”。

試了以下方法:

1.首先區分文件格式是2003,還是2007。 參考原文:https://blog.csdn.net/beyond__devil/article/details/53283352

 if($type == 'excel2003')
{
header('Content-Type: application/vnd.ms-excel'); header("Content-Disposition: attachment;filename='{$fileName}'"); header('Cache-Control: max-age=0'); $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); }
else{ header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header("Content-Disposition: attachment;filename='{$fileName}'"); header('Cache-Control: max-age=0'); $objWriter = \PHPExcel_IOFactory:: createWriter($objPHPExcel, 'Excel2007'); $objWriter->save( 'php://output'); }

原因:

1.發送header()頭之前,不知道又啥特殊字符輸出(可能是BOM,也可能是其他),導致php報錯!然后將報錯內容輸出到了Excel

2.極大可能是:文件BOM頭問題,生成的Excel文件頭部添加了BOM頭!

解決方案:

1.在輸出Excel前,緩沖區中處理BOM頭(可能是其他字符)

ob_end_clean();

ob_start();

在header()函數調用之前,清楚之前的錯誤輸出!

2.有人第一步過后,問題未解決。通過ob_get_contents()查看導出內容,並未發現BOM頭。

再就是應用了框架,返回的靜態頁輸出成了excel文件。

試了以上方法后,還是沒有問題,最后查看導出的文件內容,意識到是跳轉到靜態頁導致的。

加上 exit($contents); 后問題解決。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM