Error : the file format or file extension is not valid. verify that the file has not been corrupted

Error : the file format or file extension is not valid. verify that the file has not been corrupted

我想在我的项目中使用 PHPSpreadsheet 库将数据导出到 excel 导出的文件,但是当我尝试打开文件时显示此错误:excel 无法打开文件,因为文件格式或文件扩展名无效。确认文件没有损坏

当我以文本形式打开文件时,我发现了这个错误:

Fatal error: Uncaught PhpOffice\PhpSpreadsheet\Writer\Exception: Could not open php:://output for writing. in C:\xampp\htdocs\GL_App\Library\PhpSpreadsheet\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Writer\Xlsx.php:218

更改这行代码

$writer->save('php:://output');

$writer->save('php://output');

应该可以。另外,如何将数据传递给excel sheet?您的数据可能已损坏。

请将此插入您的代码后 autoload.php

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

我有同样的问题,我的解决方案在这里。只需将代码放在下面:

ob_end_clean();

代码:

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

        $writer->save('php://output'); // download file