我使用PhpSpreadsheet库创建一个xls并下载它,但文件已损坏。 xls将被写入输出流,而不会创建文件。
我试图创建一个空的电子表格,但失败了。您可以在以下代码示例中看到它:
$spreadsheet = new Spreadsheet();
$writer = new Xls($spreadsheet);
header('Content-Type:application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Auswertung_Allgemeinkosten.xls"');
header("Pragma: no-cache");
header("Expires: 0");
header('Cache-Control: max-age=0');
$writer->save('php://output');
如果我打开下载的文件,则会显示以下消息:
“'Auswertung_Allgemeinkosten.xls'的文件格式和扩展名不匹配。该文件可能已损坏或不安全。除非您信任它的来源,否则请不要打开它。是否要打开它?” >
文件的外观如下:
答案 0 :(得分:0)
为什么不使用空模板呢?
$path = "<PATH TO EXCEL>/empty.xlsx";
$targetPath= "<PATH TO TARGET>";
//generate Reader
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
//Gen workbook
$spreadsheet = $reader->load($path);
//Do Your Stuff
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save($targetPath);
答案 1 :(得分:0)
这对我有帮助:
$filename = 'Auswertung_Allgemeinkosten.xlsx';
$writer->save($filename);
header('Content-disposition: attachment; filename='.$filename);
header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Length: ' . filesize($filename));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
ob_clean();
flush();
readfile($filename);
unlink($filename);