I am creating a CSV file from a js object by supplying a filename, comma separated headers, and a data key-value object. However, when I go to download the file, I am facing the following issues:
- Chrome: File downloads, but the file is unnamed and has no file extension
- IE: File doesn't even download.
Here is my JS code:
function createCSV(filename, headers, data) {
var csvContent = "data:text/csv;charset=utf-8," + headers;
data.forEach(function(d, index) {
var dataString = "";
var i = 0;
for ( var key in d) {
if (d[key] == 'null')
dataString += '\"\"';
else
dataString += "\"=\"\"" + d[key] + "\"\"\"";
if (i < Object.keys(d).length - 1)
dataString += ",";
i++;
}
if (index < data.length)
csvContent += "\n";
csvContent += dataString;
});
var filename = filename + ".csv"
var link = document.createElement("a");
link.setAttribute("href", encodeURI(csvContent));
link.setAttribute("download", filename);
actuateLink(link);
}
function actuateLink(link)
{
var allowDefaultAction = true;
if (link.click)
{
link.click();
return;
}
else if (document.createEvent)
{
var e = document.createEvent('MouseEvents');
e.initEvent('click', true, true);
allowDefaultAction = link.dispatchEvent(e);
}
if (allowDefaultAction)
{
var f = document.createElement('form');
f.action = link.href;
document.body.appendChild(f);
f.submit();
}
}