6

我正在使用 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');

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

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

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

4

1 回答 1

25

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

$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 创建了一个缓冲区,并且在保存电子表格后不会关闭它。通过添加“模具”;在最后一行之后,它解决了这个问题......

所以最终代码:

$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;

希望能帮助到你 !

于 2019-03-13T10:21:13.803 回答