I had a recent requirement of exporting a report in HTML to an Excel file using PHP. Now, there is no built in PHP extension which can help us in this regard. So the option that remains is to allow the web server to download the Excel file to user’s computer and that would be it.
First thing you need to do is to tell the web sever that we would be outputting the content in Excel. So the following line should be there at the start
After that you can provide a name for the exported Excel file so it can be downloaded by that name onto the user’s computer. This is optional but its better as the file names uniquely generated may confuse the user.
header('Content-Disposition: filename="<enter filename here>.xls"');
Now we will write the actual code which will be exported. If you have viewed an Excel sheet before you will know its a combination of rows and columns which display as a spreadsheet. We will use an HTML table for this purpose. Take the following HTML table for example. If you echo the following HTML table .
|1||Adeel||Karachi||123 456 email@example.com|
|2||Sarfraz||Lahore||234 567 firstname.lastname@example.org|
You can download the complete code from my GitHub
Hope the above helped