Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JavaScript variable value to csv file

I have a comma separated variable in my .js file, for example:

var out='';
out+="1,val1,val2,val3,val4\n";
out+="2,val1,val2,val3,val4\n";
out+="3,val1,val2,val3,val4\n";

I am displaying this value in a browser using document.write(out);.
I would like the out variable to be downloadable as a .csv file.

From data stored in a variable, is there any way to create a csv file and its associated download link in JavaScript?

jsFiddle

like image 856
RavatSinh Sisodiya Avatar asked Jun 14 '13 07:06

RavatSinh Sisodiya


People also ask

How do I download a CSV file in Javascript?

Click on the given Export to HTML table to CSV File button to download the data to CSV file format. The file will download by the name of person. csv. You can open this file in MS-Excel to see the data contained inside it.

What is CSV file in Javascript?

Introduction. A CSV is a plain text file format for storing tabular data. The CSV file uses a comma delimiter to separate values in table cells, and a new line delineates where rows begin and end.


1 Answers

Depends on browser support, but that's getting pretty good with new browsers: http://jsfiddle.net/3fMeL/2/

var CSV = [
    '"1","val1","val2","val3","val4"',
    '"2","val1","val2","val3","val4"',
    '"3","val1","val2","val3","val4"'
  ].join('\n');

window.URL = window.webkitURL || window.URL;

var contentType = 'text/csv';

var csvFile = new Blob([CSV], {type: contentType});

var a = document.createElement('a');
a.download = 'my.csv';
a.href = window.URL.createObjectURL(csvFile);
a.textContent = 'Download CSV';

a.dataset.downloadurl = [contentType, a.download, a.href].join(':');

document.body.appendChild(a);

So the first item is the Blob object, this creates the object that can be downloaded. https://developer.mozilla.org/en-US/docs/Web/API/Blob (http://caniuse.com/#search=blob)

The next part is the download attribute of the link, which informs the browser to download the CSV file rather than opening it in the browser window. (http://caniuse.com/#feat=download)

like image 182
Lee Kowalkowski Avatar answered Oct 02 '22 15:10

Lee Kowalkowski