gpt4 book ai didi

excel - PhpSpreadsheet 正在损坏文件

转载 作者:行者123 更新时间:2023-12-02 11:04:29 28 4
gpt4 key购买 nike

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

We found a problem with some content in filename.xlsx. Do you want us to try and recover as much as we can? If you trust the source of this workbook, click Yes.

我已将所有内容剥离回以下代码。我打开的模板文件是一个全新的 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 completed file level validation and repair. Some parts of this workbook may have been repaired or discarded.

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

最佳答案

不知道你的问题解决了吗,我也遇到了同样的问题。我的代码如下所示:

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

希望对你有帮助!

关于excel - PhpSpreadsheet 正在损坏文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46092318/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com