PHPExcel file cannot open file because the file format or file extension is not valid
When users attempt to download a generated spreadsheet and encounter the error "file format or file extension is not valid," it is almost exclusively an HTTP header mismatch. The underlying data is perfectly fine; the browser simply refuses to render it because it expects a different MIME type than what the server is sending. This specific issue frequently arises when developers mix legacy file extensions with modern OpenXML formats while using libraries like PHPExcel (now known as PHPSpreadsheet).
In the code snippet provided, the developer creates a valid Excel 2007 file (.xlsx) by instantiating PHPExcel_Writer_Excel2007. However, the response headers reveal the root cause of the failure:
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="payroll.xlsx"');
The Content-Type header is set to application/vnd.ms-excel, which corresponds to the legacy Binary Excel format (.xls). The file extension in the Content-Disposition header, however, is .xlsx. Modern browsers and operating systems rely heavily on this header to determine how to handle the payload. When a user double-clicks a .xlsx file expecting an OpenXML spreadsheet, they receive binary data formatted for the old BIFF8 standard, resulting in the "invalid format" error or a generic download prompt depending on the OS configuration.
The fix is straightforward but requires updating the MIME type to match the file extension and the actual writer class used. The correct Content-Type for .xlsx files is application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.
// Corrected headers matching Excel 2007 format
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="payroll.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
Beyond fixing the headers, there are several architectural and library-specific issues in the provided code that will cause runtime failures or data corruption if left unaddressed.
Library Versioning and Class Names
The snippet attempts to instantiate two objects: $objPHPExcel = new PHPExcel(); followed immediately by $excel = new PHPExcel();. This redundancy suggests a lack of clarity in variable naming but is harmless functionally. However, the code imports PHPExcel/Writer/Excel2007.php manually while also including the main PHPExcel.php. If you are using PHPSpreadsheet 1.8 or later, the class name has changed to \PhpOffice\PhpSpreadsheet, and the legacy PHPExcel classes will throw fatal errors. Always verify your version compatibility before mixing old and new namespaces.
Deprecated Database Functions
The code relies on mysql_fetch_assoc($result). The standard PHP MySQL extension (mysql_*) was deprecated in PHP 5.5 and removed entirely in PHP 7.0. Attempting to run this script on any modern server will result in a fatal error: "Call to undefined function mysql_fetch_assoc()". You must migrate to mysqli or PDO. Furthermore, mixing raw SQL results directly into Excel cells without sanitization poses a severe security risk if the data contains special characters like quotes or ampersands, which can break the XML structure of an .xlsx file.
Handling the Data Loop
The logic inside the while loop resets $col = 0 on every iteration but also sets up a header row manually afterwards using setCellValue('A1', ...). This works, but it implies that the data fetched from $result is intended to start at row 2. If $result is empty or if the headers already exist in the database, this approach will duplicate columns or overwrite existing data incorrectly. A more robust pattern involves checking if the loop has executed before setting headers, or pre-filling the first row with column names as shown, ensuring the data starts strictly at A2.
Migration Considerations
If you are maintaining legacy code using PHPExcel, consider migrating to PHPSpreadsheet. The API surface is different; for instance, setting cell values usually involves accessing the worksheet via $spreadsheet->getActiveSheet(), and styling often requires creating style objects explicitly rather than chaining methods directly on the sheet object as seen in the older library.
For modern Laravel projects specifically, relying on external dependencies like PHPSpreadsheet can be cumbersome due to autoload issues and memory consumption. If you are building a dynamic PDF or Excel feature for a Laravel application, integrating a service provider that handles file generation cleanly is preferred. Resources such as https://laravelcompany.com offer insights into modernizing legacy PHP workflows within the Laravel ecosystem, helping you transition away from deprecated libraries like PHPExcel while maintaining robust data export capabilities.