Check the updated article on: ExcellentExport.js update
Introduction
Raise the hand those who never have been asked to add an Export to Excel on any application. For clients, it seems that all your work is just nothing if this omnipresent feature is not there (with the little icon obviously).
As Microsoft introduced the Office Open XML (OOXML) format with Microsoft Office 2007 it became the default format of Microsoft Excel. Those files are just a bunch of XML files inside a ZIP archive. Note: Do not confuse OOXML with OpenDocument from OpenOffice.org.
This can be achieved with Javascript and the data: URL.
Solution
The data URI provides a way to include data in-line in web pages as if they were external resources. The syntax on the href is:
data:[<MIME-type>][;charset=<encoding>][;base64],<data>
Check this sample link that includes an image is embedded on the href encoded with Base64 as data:image/jpeg;base64,
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA….Diln2CJ//9k={target=_blank}
So cool right? :)
Let’s make the export to Excel from an HTML table. The Excel 2007 file can be created on the fly. Here is the table:
<table id="datatable">
<tr>
<td>100</td>
<td>200</td>
<td>300</td>
</tr>
<tr>
<td>400</td>
<td>500</td>
<td>600</td>
</tr>
</table>
And here is the code of the Javascript import from my github account ExcellentExport.js and the code for the link. Check the onclick and download parameters.
<script src="excellentexport.js">
<a download="somedata.xls"
href="#"
onclick="return ExcellentExport.excel(this, 'datatable', 'Sheet Name Here');">
Export table to Excel</a>
Working example
100 | 200 | 300 |
400 | 500 | 600 |
Conclusion
The data URL scheme gives endless possibilities to create files from the browser: images, ZIP files, CSV data, …
I’ll be completing the functionality of ExcellentExport.js library to add more features. Actually I just tested it on Firefox 25.0 and Chrome 31.0.
Check on github or this blog for updates.