Home » excel » Why my Excel file does not open with PHP?

Why my Excel file does not open with PHP?

Posted by: admin May 14, 2020 Leave a comment


I need to do data export in Excel file, I thougt so easy 🙂

I use PhpSpreadsheet library (https://github.com/PHPOffice/PhpSpreadsheet)

I try with PhpSpreadsheet samples and doing simple things :

  1. create Xlsx Spreadsheet
  2. Save on hardrive
  3. Open in browser for download

There is my code :

require_once $this->config->application->libraryDir . 'PhpSpreadsheet-master/vendor/autoload.php';

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');

$writer = new Xlsx($spreadsheet);
$fileName = 'export/hello_world.xlsx';

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

The result : The file was created on folder ‘export’, I can open it with Windows.
But, when file is download on default folder of downloads, I can not open it. I have this error : Excel has encountered unreadable content

Have you an idea why this problem?

How to&Answers:

Try exiting after $writer->.save('php://output'). For troubleshooting, Prior to your header(...)s, try exiting to make sure there is no output.

And since you know $writer->save($fileName) works, you could try, instead of calling $writer->save('php://output') you could do $writer->save($fileName); header(...); echo file_get_contents($fileName); Trying different content-types might be worthwhile too