PHPOffice 写入新文件时出现 fatal error

标签 php phpspreadsheet phpoffice

我正在使用 this从我的 PHP 脚本创建 .xlsx 文件的库。

正在关注 this指南,我已经尝试将一些数据导出到名为 hello.xlsx 的文件中。

但是,此错误会显示以下消息:

Warning: ZipArchive::close(): Failure to create temporary file: Permission denied in vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer

Fatal error: Uncaught PhpOffice\PhpSpreadsheet\Writer\Exception: Could not close zip file hello.xlsx. in vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx.php on line 399

PhpOffice\PhpSpreadsheet\Writer\Exception: Could not close zip file hello.xlsx. in /vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx.php on line 399

该文件在执行前不存在,所以我得到了一些错误。我总是可以尝试 touch hello.xlsx 并更改我的脚本以读取该文件并附加数据,但实际上,每次运行脚本时我都在尝试编写一个新文件。

这是我的(简化的)代码:

require_once 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

$sheet->setCellValue('A1', 'foo');
$sheet->setCellValue('B1', 'bar');
$sheet->setCellValue('C1', 'foobar');
$sheet->setCellValue('D1', 'trey is the best');

$writer = new Xlsx($spreadsheet);
$writer->save('hello.xlsx');

转到错误中的那些行显示这段代码:

// Close file
if ($zip->close() === false) {
    throw new WriterException("Could not close zip file $pFilename.");
}

对我来说,这并不是一条有助于调试问题的消息。

我在这方面找到了各种 SO 帖子:

不幸的是,接受的答案无效(将代码更改为 $writer->save($_SERVER['DOCUMENT_ROOT'].'/hello.xlsx'))。

我还尝试了 SaveFiaTempFile 函数,但它只会输出一堆有趣的字符。

我也不想将我的文件夹/文件权限设置为 777,因为这在膜中是疯狂的。

除了更改所有权之外,这个已接受的答案并没有真正表明正确的做法是 IMO,但是..将什么更改为什么?

那么,我该如何着手解决/调试问题,而不需要真正继续下去呢?

谢谢:)

更新

所以我想我应该仔细检查一下,我在我的 project_root 中创建了一个名为 tmp 的文件夹。我更改了代码以写入 $_SERVER['DOCUMENT_ROOT']。 '/tmp/hello.xlsx' 它仍然给出了错误。

但是,我想“嘿,让我们开个玩笑吧”,令我惊讶的是数据都在那里,一切似乎都正常..但无论出于何种原因,它仍然会收到错误在我的浏览器中出现下载弹出窗口..

最佳答案

我找到了创建动态 Xlsx 文件的解决方案:

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="hello.xlsx"');
header('Cache-Control: max-age=0');

$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');

在这里,我们实际上只是将浏览器重定向到 php://output 并下载文件。

关于PHPOffice 写入新文件时出现 fatal error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55121561/

相关文章:

php - 在 Laravel 中同时执行多个查询

php - 我在 Windows 8 上安装了 Xampp。当我尝试在 XAMPP 控制面板中启动 MySql 时,出现以下消息,并且 MySql 无法启动

php - 找不到类 'ZipArchive'

PHPSpreadsheet 自动行高不适用于 LibreOffice 最新版本

php - 无法正确设置 set PrintArea

php - 使用 PHP Word 阅读 MS Word 文档

php - 使用 xampp 在 php 中连接 oracle 数据库

php - 当请求中有特殊字符时重定向到 root - laravel 5

php - 如何获取 excel 单元格中存在的图像?

php - 使用 PHP 获取 xls(Excel 文件) PHPOffice PHPExcel