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 show this value in the browser using document.write(out); .
I would like the out variable to be loaded as a .csv file.

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

jsFiddle

+7
source share
2 answers

Depends on browser support, but it gets really 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 element is a Blob object, which creates an 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 link download attribute, which informs the browser about the need to download the CSV file, and not open it in the browser window. ( http://caniuse.com/#feat=download )

+18
source

there is a jquery plugin for the output file on the client side without interacting with the server,

https://github.com/dcneiner/Downloadify

0
source

All Articles