Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export javascript data to CSV file without server interaction

If we were on a nodeJS server, we could write a header, set a mime type, and send it:

res.header("Content-Disposition", "attachment;filename="+name+".csv");  res.type("text/csv"); res.send(200, csvString); 

and because of the headers, the browser will create a download for the named csv file.

When useful data is generated in a browser, one solution to getting it in a CSV file is to use ajax, upload it to the server, (perhaps optionally save it there) and get the server to send it back with these headers to become a csv download back at the browser.

However, I would like a 100% browser solution that does not involve ping-pong with the server.

So it occurred to me that one could open a new window and try to set the header with a META tag equivalent.

But this doesn't work for me in recent Chrome.

I do get a new window, and it contains the csvString, but does not act as a download.

I guess I expected to get either a download in a bottom tab or a blank new window with a download in a bottom tab.

I'm wondering if the meta tags are correct or if other tags are also needed.

Is there a way to make this work without punting it to the server?

JsFiddle for Creating a CSV in the Browser (not working - outputs window but no download)

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"); console.log(csvString); var csvWin = window.open("","",""); csvWin.document.write('<meta name="content-type" content="text/csv">'); csvWin.document.write('<meta name="content-disposition" content="attachment;  filename=data.csv">  '); csvWin.document.write(csvString); 
like image 412
Paul Avatar asked Jul 24 '13 14:07

Paul


People also ask

How do I export HTML table data as .CSV file?

right-click anywhere in the table and select 'copy whole table' start up a spreadsheet application such as LibreOffice Calc. paste into the spreadsheet (select appropriate separator character as needed) save/export the spreadsheet as CSV.

How do you process a CSV file in JavaScript?

parse("http://example.com/bigfoo.csv", { download: true, step: function(row) { console. log("Row:", row. data); }, complete: function() { console. log("All done!"); } });

Can JavaScript parse CSV?

To convert or parse CSV data into an array , you need to use JavaScript's FileReader class, which contains a method called readAsText() that will read a CSV file data and parse the result as a string text.


2 Answers

There's always the HTML5 download attribute :

This attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource so that when the user clicks on the link they will be prompted to save it as a local file.

If the attribute has a value, the value will be used as the pre-filled file name in the Save prompt that opens when the user clicks on the link.

var A = [['n','sqrt(n)']];  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(',')); }  var csvString = csvRows.join("%0A"); var a         = document.createElement('a'); a.href        = 'data:attachment/csv,' +  encodeURIComponent(csvString); a.target      = '_blank'; a.download    = 'myFile.csv';  document.body.appendChild(a); a.click(); 

FIDDLE

Tested in Chrome and Firefox, works fine in the newest versions (as of July 2013).
Works in Opera as well, but does not set the filename (as of July 2013).
Does not seem to work in IE9 (big suprise) (as of July 2013).

An overview over what browsers support the download attribute can be found Here
For non-supporting browsers, one has to set the appropriate headers on the serverside.


Apparently there is a hack for IE10 and IE11, which doesn't support the download attribute (Edge does however).

var A = [['n','sqrt(n)']];  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(',')); }  var csvString = csvRows.join("%0A");  if (window.navigator.msSaveOrOpenBlob) {     var blob = new Blob([csvString]);     window.navigator.msSaveOrOpenBlob(blob, 'myFile.csv'); } else {     var a         = document.createElement('a');     a.href        = 'data:attachment/csv,' +  encodeURIComponent(csvString);     a.target      = '_blank';     a.download    = 'myFile.csv';     document.body.appendChild(a);     a.click(); } 
like image 158
adeneo Avatar answered Oct 01 '22 20:10

adeneo


@adeneo answer works for Firefox and chrome... For IE the below can be used.

if (window.navigator.msSaveOrOpenBlob) {    var blob = new Blob([decodeURIComponent(encodeURI(result.data))], {      type: "text/csv;charset=utf-8;"    });    navigator.msSaveBlob(blob, 'FileName.csv');  }
like image 40
Manu Sharma Avatar answered Oct 01 '22 19:10

Manu Sharma