0

I use the PhpSpreadsheet library to create a xls and download it but the file is corrupted. The xls will be written in the output stream, no file is created.

I tried to create an empty spreadsheet and it fails. You can see it in the following code example:

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

If I open the downloaded file the following message is shown:

"File format and extension of 'Auswertung_Allgemeinkosten.xls' don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?"

This is how the file looks like:

enter image description here

MichaB
  • 495
  • 7
  • 20

2 Answers2

0

Why not use a empty Template and do it so?

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

This is what helped me:

    $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);
MichaB
  • 495
  • 7
  • 20