Shubh Shubh - 3 months ago 64
Javascript Question

Javascript/ jQuery : Exporting data in CSV not working in IE

I need to Export Data displayed in a Table to CSV Format. I have tried lot many things but couldn't get it working for IE 9 and above.

I have created a dummy fiddle with my code.

var data = [
["name1", "city1", "some other info"],
["name2", "city2", "more info"]
];//Some dummy data

var csv = ConvertToCSV(data);//Convert it to CSV format
var fileName = "test";//Name the file- which will be dynamic

if (navigator.userAgent.search("MSIE") >= 0) {
//This peice of code is not working in IE, we will working on this
//TODO
var uriContent = "data:application/octet-stream;filename=" + fileName + '.csv' + "," + escape(csv);
window.open(uriContent + fileName + '.csv');
} else {
var uri = 'data:text/csv;charset=utf-8,' + escape(csv);
var downloadLink = document.createElement("a");
downloadLink.href = uri;
downloadLink.download = fileName + ".csv";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}


I have seen many of the links in Stackoverflow, but couldn't find anything that's working with IE9 or above. Like @ Terry Young explains in how-to-data-export-to-csv-using-jquery-or-javascript

Also, tried-

var csv = ConvertToCSV(_tempObj);
var fileName = csvExportFileName();
if (navigator.appName != 'Microsoft Internet Explorer') {
window.open('data:text/csv;charset=utf-8,' + escape(str));
}
else {
var popup = window.open('', 'csv', '');
popup.document.body.innerHTML = '<pre>' + str + '</pre>';
}


Not sure how to fix it. I don't want to hit the server and export my CSV (the requirement say so).

Answer

After using Javascript it will solve your problem.

Use this for IE,

var IEwindow = window.open();
IEwindow.document.write('sep=,\r\n' + CSV);
IEwindow.document.close();
IEwindow.document.execCommand('SaveAs', true, fileName + ".csv");
IEwindow.close();

For more information i have written tutorial on that, see - Download JSON data in CSV format Cross Browser Support

Hope this will be helpful for you.