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 :
- create Xlsx Spreadsheet
- Save on hardrive
- 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'; $writer->save($fileName); // header('Location: '.$fileName); 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');
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?
$writer->.save('php://output'). For troubleshooting, Prior to your
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