问题描述
我正在使用PhpSpreadsheet修改现有文件并将其发送到浏览器,但是每次下载文件时,excel都会给我以下错误:
I am using PhpSpreadsheet to modify an existing file and send it to the browser, but every time I download the file excel gives me the following error:
我已将所有内容剥离回以下代码.我要打开的模板文件是一个全新的excel文件,未对其进行任何编辑(以避免该模板中已经存在该错误的可能性).我可以从驱动器中打开此文件,而不会出现任何问题.
I have stripped back everything to the following code. The template file that I am opening is a brand new excel file, with no edits made to it (to avoid the potential that the error already exists in the template). I can open this file from the drive without any issues.
$spreadsheet = IOFactory::load(storage_path() ."\Template - English.xlsx");
// Redirect output to a client’s web browser (Xlsx)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="filename.xlsx"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
完成修复过程后,我从Excel中收到以下消息,并且一切正常.
Once I go through the repair process I get the following message from Excel, and everything seems to work fine.
****当我使用$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
** **The same error occurs when I generate a new file using $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
推荐答案
我不知道您是否解决了您的问题,但我有同样的想法.我的代码如下:
I don't know if you solved your issue but I had the same.My code looks like this :
$strFilename = sprintf('%s_%s_subscriptions', date('Y-m-d-H-i'), $alias);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$strFilename.'.xlsx"');
header('Cache-Control: max-age=0');
$writer = IOFactory::createWriter($objSpreadsheet, 'Xlsx');
$writer->save('php://output');
Excel会提示与您相同的错误.但是看起来PHPSpreadSheet创建了一个缓冲区,并且在保存电子表格后不会将其关闭.通过添加模具";在最后一行之后,它解决了问题...
And Excel prompt the same error as you. But it looks like PHPSpreadSheet create a buffer and doesn't close it once you save the spreadsheet.By adding a "die;" after the final line, it solved the issue...
最后的代码:
$strFilename = sprintf('%s_%s_subscriptions', date('Y-m-d-H-i'), $alias);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$strFilename.'.xlsx"');
header('Cache-Control: max-age=0');
$writer = IOFactory::createWriter($objSpreadsheet, 'Xlsx');
$writer->save('php://output');
die;
希望有帮助!
这篇关于PhpSpreadsheet损坏文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!