I need make xlsx
file download from my site (but not from directly open file url like this: http://site.com/file.xlsx
)
So, this is php code
$file = "somefile.xlsx";
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
file is downloaded, his extension is .xlsx
, but when trying open this file in ms excel, file not opened and I got error : excel cannot open the file.xlsx because the file format or file extension is not valid
Tell please, why this happened? where I am wrong?
I am going to tell you how you can create an excel file with XLSX extension. Download PHPExcel library from here. To export data into excel file you need to follow below steps. First of all, you need to create a table that contains some data in this example, I am going to use Country Table that we create for PHP pagination class with Bootstrap 4.
EasyXLS Excel library can be used to import Excel files with PHP on Windows, Linux, Mac or other operating systems. The integration vary depending on the operating system or if .NET Framework or Java is chosen: 1. EasyXLS on Windows using .NET Framework (COM+) with PHP
$fileName – Define the name of the excel file to be downloaded. $fields – Define the column named of the excel sheet. $excelData – Add the first row to the excel sheet as a column name. Fetch member’s data from the database and add to the row of the excel sheet. Define headers to force the file to download. Render data of excel sheet.
The $fileName variable defines the name of the excel file. The Content-Disposition and Content-Type headers force the excel file to download. Run the loop through each key/value pair in the $data array.
After many years, I got same problem, and after searching, I got here again ))
This is solution, that worked for me:
$file = "somefile.xlsx";
// define file $mime type here
ob_end_clean(); // this is solution
header('Content-Description: File Transfer');
header('Content-Type: ' . $mime);
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file) . "\"");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile($file);
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