tok*_*000 0 php phpspreadsheet
我想在我的项目中使用 PHPSpreadsheet 库将数据导出到导出的文件中,但是当我尝试打开文件时,此错误显示:excel 无法打开文件,因为文件格式或文件扩展名无效。验证文件未损坏
注意:我在我的项目中使用 MVC,所以控制器中的代码如下:
protected function Excel($view, $variables = [])
{
require_once PATH_LIBRARY_FOLDER.'PhpSpreadsheet\vendor\autoload.php';
ob_start();
// Note: make new Spreadsheet object
$spreadsheet = new Spreadsheet();
// Note: get current active sheet (frist sheet)
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
extract($variables);
include($this->viewPath.$view.'.php');
// Note: set the header to define it is excel file
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
// Note: set the header to define excel file name
header("Content-Disposition: attachment;filename=\"filename.xlsx\"");
header("Cache-Control: max-age=0");
// Note: create IOFactory object
$writer = IOFactory::createWriter($spreadsheet, 'xlsx');
ob_get_clean();
$writer->save('php:://output');
exit();
}
Run Code Online (Sandbox Code Playgroud)当我以文本形式打开文件时,我发现了这个错误:
致命错误:未捕获的 PhpOffice\PhpSpreadsheet\Writer\Exception:无法打开 php:://output 进行写入。在 C:\xampp\htdocs\GL_App\Library\PhpSpreadsheet\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Writer\Xlsx.php:218
小智 5
我有同样的问题,我的解决方案在这里。只需将代码放在下面:
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
Run Code Online (Sandbox Code Playgroud)