Last Updated: April 27, 2017
·
2.466K
· CodeAddict

How to download a Javascript Array as a CSV file

function download (content, fileName, mimeType)
{
var a = document.createElement('a');
mimeType = mimeType || 'application/octet-stream';
if (navigator.msSaveBlob) { // IE10
return navigator.msSaveBlob(new Blob([content], { type: mimeType }), fileName);
} else if ('download' in a) { //html5 A[download]
a.href = 'data:' + mimeType + ',' + encodeURIComponent(content);
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
return true;
} else { //do iframe dataURL download (old ch+FF):
var f = document.createElement('iframe');
document.body.appendChild(f);
f.src = 'data:' + mimeType + ',' + encodeURIComponent(content);

    setTimeout(function() {
        document.body.removeChild(f);
    }, 300);
    return true;
}

}
//Use like this
var array = []
var len = array.length;
var csvContent = "";
for(var i = 0; i < len; i++) {
csvContent += array[i] + '\n';
}
var csvName = 'records.csv';

download(csvContent, csvName, 'text/csv');

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside