After creating xlsx file with phpspreadsheet, forcing download with readfile produce an incorrect file

  excel, php, readfile, spreadsheet

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!!

This is the content of the file downloaded with readfile:
enter image description here

It starts with csv data and then the excel file.

This other one is the same file downloaded with link:
enter image description here

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?

Thank you

Source: Ask PHP

LEAVE A COMMENT