Javascript Base64 Turns a Table Into CSV
By Ryan Florence, published 2010-04-04
Part of the issue Migrated Articles From Original Site Structure..
I’ve got a web application (aka: my resume) I wrote to track my business expenses, billing, invoicing, etc. In the app are several tables full of data. My accountant likes me to give him a bunch of stuff in excel or csv format. I’ve got a button on each interface that opens a new window with the table data in CSV.
Previously, the app used server-side code to output the CSV. This year I decided to tinker with MooTools and Base64 and see if I could avoid the server altogether to create the CSV.
What is Base64?
From Wikipedia:
Base64 encoding schemes are commonly used when there is a need to encode binary data that needs be stored and transferred over media that is designed to deal with textual data. This is to ensure that the data remains intact without modification during transport.
Success!
Thanks to webtoolkit.info for the code I used to implement these MooTools Base64 encoding methods.
Download Base64 from the MooTools forge.
Explanation
Base64 usage is quite simple:
var str = "I am a string";
var data = str.toBase64();
var decoded = str.decodeBase64();
Then I’ve got a little element extension to create CSV out of a table, which I should probably release on the forge sometime:
Element.implement({
toCSV: function(row, field){
var row = row || 'tr',
field = field || 'td',
csv = '';
this.getElements(row).each(function(row){
csv += row.getElements(field).map(function(td){ return '"'+td.get('text').replace(/(')+/,"\\'")+'"'; }).join(',') + "\n";
});
return csv;
}
});
// usage
$('some_table').toCSV();
The real trick is getting the new window to contain the string:
var data = $('my_table').toCSV().toBase64();
window.open("data:text/csv;base64," + data, "csvWindow");
Cool trick? Yes! Actually, since I’m using this, it’s more than a trick, it’s actually quite handy. The only thing I lost is the ability to send the file as a Content Type: attachment
straight to the downloads folder in Safari.
Browser Support / Behavior
- IE8 - Doesn’t work, ofc, but I don’t use it for my billing app so I don’t care
- Chrome - Doesn’t work :(
- Safari - Works great, opens data in a new window
- Firefox 3.6 - Works even better with a prompt to save the file, which is exactly what I want …