Browser and length independent CSV download code

17-09-2015

Downloading a csv string as a file on browser can be troublesome. Some techniques don’t work for very long CSV strings and some techniques only work on some browsers.

Below code is tested on Internet Explorer 11, Firefox 27.0.1, and Chrome 45.0.2454.93 m

And you can extend the code (where it alerts user that their browser isn’t compatible) to support more browsers.

Please comment if you do so, it will help others.


var csvString = your csv string;
var blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob)
{ // IE 10+
navigator.msSaveBlob(blob, fileName);
}
else
{
var link = document.createElement("a");
if (link.download !== undefined)
{ // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", fileName);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
else
{
// extend support for additional browsers here.
alert('Sorry, your browser does not support this export. Please contact support');
}
}

Sources:
http://stackoverflow.com/questions/27115748/download-attribute-not-working-in-firefox
http://blog.eliacontini.info/post/79860720828/export-to-csv-using-javascript-and-the-download

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: