How to export to Excel from HTML using PHP

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

header('Content-Type: application/');

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 .

1AdeelKarachi123 456 7890[email protected]
2SarfrazLahore234 567 8901[email protected]

You can download the complete code from my GitHub

Hope the above helped

Leave a Comment