Export PHP results to Excel

Lets say I use PHP to assemble a table of figures, some stored in a database and others calculated onto a page. Can I export these figures and calculations “as is” to Excel?

Kind of like this:

year		2007	2008	2009	2010
procedures	100	150	160	200
units		22	30	36	40

you can try with Pear Spreadsheet_Excel_Writer ( Package for generating Excel spreadsheets (.xls) )

Take a look at the detail description here


You can also use PHP to generate CSV files instead of HTML pages simply by using:

header('Content-type: text/comma-separated-values');
header('Content-Disposition: attachment; filename="somefilename.csv"');

and then echoing the data with the necessary commas in between.

That will automatically offer the file for download rather than writing the output to a file on the server and if you select Open instead of Save then it will import itself directly into Excel.

I found that to be the easiest way of allowing visitors to a site to extract data directly into Excel without the need to save any files on the server in order to offer them for download.

There’s also PHPExcel.

Excel understands CSV’s.