Easy Excel export from PHP

Written: Mar 8th 2008, 09:10

Here is a simple way of exporting data to excel documents. With utf-8 encoding you can use special nordic letters like ø, æ and å.

<span class="Apple-style-span" style="font-family: Arial; line-height: 14px; white-space: normal;"><div>&lt;?php</div><div>header("Expires: 0");</div><div>header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");</div><div>header("Cache-Control: no-store, no-cache, must-revalidate");</div><div>header("Cache-Control: post-check=0, pre-check=0", false);</div><div>header("Pragma: no-cache");</div><div>header("Content-type: application/vnd.ms-excel;charset:UTF-8");</div><div>header("Content-Disposition: attachment; filename=filename.xls"); </div><div>print "\n"; // Add a line, unless excel error..</div><div>?&gt;</div><div>&lt;table border="1"&gt;</div><div><span class="Apple-tab-span" style="white-space:pre">	</span>&lt;tr&gt;</div><div><span class="Apple-tab-span" style="white-space:pre">		</span>&lt;th&gt;header 1&lt;/th&gt;</div><div><span class="Apple-tab-span" style="white-space:pre">		</span>&lt;th&gt;header 2&lt;/th&gt;</div><div><span class="Apple-tab-span" style="white-space:pre">	</span>&lt;/tr&gt;</div><div><span class="Apple-tab-span" style="white-space:pre">	</span>&lt;tr&gt;</div><div><span class="Apple-tab-span" style="white-space:pre">		</span>&lt;td&gt;data 1&lt;/td&gt;</div><div><span class="Apple-tab-span" style="white-space:pre">		</span>&lt;td&gt;data 2 - nordic letters æ, æ, å&lt;/td&gt;</div><div><span class="Apple-tab-span" style="white-space:pre">	</span>&lt;/tr&gt;</div><div>&lt;/table&gt;</div></span>

Its really all about the headers. For the body of the document, Excel is not very choosy, we just hand it a regular HTML table, and thats it. 

Back to posts list