I’m creating an xlsx file with PhpSpreadsheet and it works correctly, but there is a strange beaviour.
After the creation of the excel file, stored in the server, if I try to force download with the following code:
header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment; filename=newfile.xlsx'); readfile ($file);
the file has an incorrect format and can not be opened in excel.
But if I download it with an html link, I can open it!
The file has its sheets composed with csv files.
I’m using this code:
$spreadsheet =PhpOfficePhpSpreadsheetIOFactory::load("./spreadsheet/example.xlsx"); // void file $reader = new PhpOfficePhpSpreadsheetReaderCsv(); $reader->setDelimiter(';'); $reader->setEnclosure(''); $reader->setSheetIndex(0); $reader->loadIntoExisting("./spreadsheet/temp.csv", $spreadsheet); // csv file created before $writer = PhpOfficePhpSpreadsheetIOFactory::createWriter($spreadsheet, "Xlsx"); $writer->save("./spreadsheet/newfile.xlsx");
Now, this file (newfile.xlsx) forced with readfile has an incorrect format. But if I create a link and download it, it’s perfect!!
It starts with csv data and then the excel file.
It’s a correct xlsx file and I can open it with excel.
Can someone help me found a solution to force download instead of creating a link?
Source: Ask PHP