PHP : Dead Easy Excel Export

This is post is now quite old and the the information it contains may be out of date or innacurate.

If you find any errors or have any suggestions to update the information please let us know or create a pull request on GitHub

Some people like their excel files. For people who want their data exported in an excel format checkout this chunk of code. It’s really easy :-)

First of all you need to download this php excel class

Now try this code:

$query = mysql_query("select * from table");
while($q = mysql_fetch_assoc($query)){
	$output[] = $q;
require_once "excel.php";
$export_file = "xlsfile://export.xls";
$fp = fopen($export_file, "wb");
if (!is_resource($fp))
    die("Cannot open $export_file");
fwrite($fp, serialize($output));
header ("Content-Type: application/x-msexcel");
header ("Content-Disposition: attachment; filename=\"exports.xls\"" );

That’s got to be the easiest thing you have ever done in PHP. Thanks goes to the excellent PHP Classes site.

Here is some further reading: PHP Excel Formula Parser PHP Excel Export class Export data directly to Excel by configuring the MIME Type Profile Option Power your PHP Business Logic with Excel Reading/Parsing Excel Spreadsheet using PHP

Tags: edmondscommerce