PhpSpreadsheet 正在损坏文件

ale*_*169 4 excel phpexcel phpoffice phpspreadsheet

我正在使用 PhpSpreadsheet 修改现有文件并将其发送到浏览器,但每次下载文件 excel 时都会出现以下错误:

我们发现 filename.xlsx 中的某些内容存在问题。您希望我们尽可能多地尝试恢复吗?如果您信任此工作簿的来源,请单击是。

我已将所有内容剥离为以下代码。我打开的模板文件是一个全新的 excel 文件,没有对其进行任何编辑(以避免模板中已经存在错误的可能性)。我可以从驱动器打开这个文件,没有任何问题。

$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');
Run Code Online (Sandbox Code Playgroud)

完成修复过程后,我会从 Excel 收到以下消息,一切似乎都正常。

Excel 完成了文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃。

**编辑:** 当我使用生成一个新文件时会发生同样的错误 $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();

小智 17

我不知道你是否解决了你的问题,但我有同样的问题。我的代码如下所示:

$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');
Run Code Online (Sandbox Code Playgroud)

Excel 提示和你一样的错误。但看起来 PHPSpreadSheet 创建了一个缓冲区,并且在保存电子表格后不会关闭它。通过添加“死”;在最后一行之后,它解决了这个问题......

所以最终代码:

$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;
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你 !

  • 嗯,‘死’就可以了。`exit;` 的作用是一样的。 (2认同)