Exporting to EXCEL

My picI’ve seen it happening to many sites and I always thought of this as impossible. I beleived that since the api is closed you cannot export into this format. It turns out that i was wrong. Well, as it turned out, not entirely… I mean the api is still closed but an XML can be parsed.

So all you have to do is write a file with the following format:

  1.  
  2.  
  3. <workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40">
  4.     <worksheet ss:name="test.xls">
  5.         </worksheet></workbook>
  6. <table><row>
  7.                 <cell><data ss:type="String">foo</data></cell>
  8.                 <cell><data ss:type="String">bar</data></cell>
  9.             </row>
  10.             <row>
  11.                 <cell><data ss:type="String">bara</data></cell>
  12.             </row></table>
  13.  

This is a perfect xls file that has two rows with two columns of data on the first and one on the second. Now, if you want to send this from a server to a browser use the following code:

  1. header("Content-type: application/octet-stream");
  2. header("Content-Disposition: attachment; filename=voters-export-".date(‘d-m-Y’).".xls");
  3. header("Content-Type: application/ms-excel");
  4. header("Pragma: no-cache");
  5. header("Expires: 0");

With this you are done!



Leave a Reply