epalla

M
a
y
29

Exporting to Excel from a Query in PHP/MySQL

May 29th 2009 2:26 pm by Matt

I’m mostly posting this for my own future reference. This is the simplest example in the world for exporting from a simple SQL query to an Excel file while preserving row headers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// assuming we got our query from an htmlspecialchars encoded, slashes added POST
$z = htmlspecialchars_decode(stripslashes($_POST['query']));
$q = mysql_query($z);
$result = '';
 
// add the row headers
$numfields = mysql_num_fields($q);
for ($i=0; $i<$numfields; $i++) {
	$result .= mysql_field_name($q, $i) . "\t";
}
 
/* cycle through the query and add each row, note the casting via &$val and the \t separators for new columns.  Using commas, semicolons, etc. will create a .csv but Excel will not interpret it correctly as an .xls download */
while ($r = mysql_fetch_assoc($q)) {
	$result .= "\n";
	foreach ($r as &$val) {
		$result .= "$val\t";
	}
 
}
 
header('Content-type: application/ms-excel');
header("Content-Disposition: attachment; filename=report.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo $result;
Make me popular!

    This entry was posted on Friday, May 29th, 2009 at 2:26 pm and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

    Comments are closed.