PHPExcel generated excel file not working. (File format or extension is invalid)
The example code of PHPExcel exceutes successfully on my local PC, the file gets downloaded to local and is opened in Excel 2007 successfully. But using the same code on my server gives an Invalid file to excel, which when I OPEN AND REPAIR, then it opens successfully.
I don't want to use the Open and Repair option, but only the Open option.
Couldn't find out the problem? Please help.
$objPHPExcel->setActiveSheetIndex(0);
//for XLSX
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="item_list.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file." It usually indicates the file is not compatible with the Excel version of the file that has come corrupt or damaged.
But Excel since 2007 saves files in the XLSX format. A mismatch between file extension and Excel version may cause the error “Excel cannot open the file because the file format or file extension is not valid”. Therefore, all you need is to modify the file format and it will become available.
If you see the 'File Format and Extension of Don't Match' error, the Excel file you are trying unsuccessfully to open is likely in fact of a different extension that the one that is currently hardwired.
Add a line ob_end_clean();
at the end of your program before the line $objWriter->save('php://output');
The code looks like: //for XLSX
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="item_list.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_end_clean();
$objWriter->save('php://output');
exit;
The file that you've posted has a single space character before the PHPExcel output... check your script to see where this might be sent to the php://output stream. Check that there's no space before your initial <?php
opening tag; watch out in particular for ?> <?php
or similar closing/opening tags. And also check any files that might be included
by your script
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With