Exporting data from a web browser to a csv file using javascript.

If you want to skip all this text and just download a working example, go ahead and scroll to the end of this post. Otherwise, read on.


There is a comprehensive answer from Terry Young on Stack Overflow with accompanying fiddle here.

Works as you’d expect on Firefox 20 and Google Chrome 26. The file exports fine in Safari 6.0.5 but won’t name the file. Instead, it’ll save your file as ‘unknown’ (no file extension) so you’ll need to go in and rename it yourself if you’re constrained to Safari.

And then there’s this answer on Stack Overflow by adeneo. It’s a little less comprehensive but equally helpful depending on what you’re looking for. Here’s the fiddle. A rough idea of what the code looks like is shown below.

var A = [['n','sqrt(n)']];  // initialize array of rows with header row as 1st item
	 
for(var j=1;j<10;++j){ A.push([j, Math.sqrt(j)]) }

var csvRows = [];
for(var i=0,l=A.length; i<l; ++i){
	    csvRows.push(A[i].join(','));   // unquoted CSV row
}
var csvString = csvRows.join('\n');

var a = document.createElement('a');
a.href     = 'data:attachment/csv,' + csvString;
a.target   ='_blank';
a.download = 'myFile.csv,' + encodeURIComponent(csvString); ;
a.innerHTML = "Click me to download the file.";
document.body.appendChild(a);

Finally, here’s a link to a downloadable gist on GitHub if you want to just get up and running straight away. It’s based on Terry Young‘s answer but modified to include table headers, and refactored so anything that gets done more than once gets its own function.

Advertisements

2 thoughts on “Exporting data from a web browser to a csv file using javascript.

  1. a.href = ‘data:attachment/csv,’ + csvString;
    should actually be
    a.href = ‘data:attachment/csv,’ + encodeURIComponent(csvString);
    or the new line chacters and spaces wont work

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s