How to export data into Excel from a browser

If you have some type of report which you would like to export into Excel then you can do so by doing the steps below in PHP:

1. Ideally you should create a separate file which should mimic the one you are trying to export into Excel. So suppose the name of your file is reports.php create another with the name of reports_excel.php

2. Do not include any images and CSS in this file as Excel will not recognize it. For e.g. if you need to change the color of the text then do it the old fashioned way by using the font tag and setting the color and size in it.

3. Once you have created the template and layout in the new file add the following lines at the top of the file:

header("content-type: application/vnd.ms-excel");
header('Content-Disposition: attachment; filename=<your_filename_here>.xls');
header('Pragma: no-cache'); 

4. Now if you run the reports.excel.php file you will see a popup which will ask you to open the Excel sheet in your browser or save it on your hard drive.

5. Save the file and open it and you will see all your data is there in Excel format.

Leave a Comment