JDEC
JDEC

Reputation: 101

How to avoid Excel "bad format error" when saving spreadsheet

Using PHPSpreadsheet saving XLSX format works OK running the default code

$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet); 
$writer->save("filename.xlsx");

But if I want to have the user to select the target directory using

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="filename.xlsx"');
header('Cache-Control: max-age=0');
$writer = IOFactory::createWriter($spreadSheet, 'Xlsx');
$writer->save('php://output');

The file saves OK but Excel 2016 does not want to open it. Excel returns the following error Excel Error

I looked through all documentation and posts but cannot find the solution.

Thanks !

Edit: Just in case, this solution does not work for me.

Edit 2: The sample provided Simple Download Xlsx works perfectly, but when doing a copy/paste for my spreadsheet, Chrome gives me a Resource interpreted as Document but transferred with MIME type application/octet-stream

Edit 3: Used ob_end_flush(); to clean any left over header in my code. The file now saves OK, but needs repair when opening in Excel. Why ?

Thanks

Upvotes: 1

Views: 972

Answers (1)

JDEC
JDEC

Reputation: 101

Solution:

Bug from PhpSpreadsheet.

When using header("Content-Type: application/vnd.ms-excel");

i.e. compatibility mode for Excel, the file opens OK.

Upvotes: 0

Related Questions