创建CSV并打开JS,而不是在IE,Chrome中工作

时间:2014-06-18 18:32:05

标签: javascript internet-explorer google-chrome csv cross-browser

我通过提供文件名,逗号分隔的标头和数据键值对象从js对象创建CSV文件。但是,当我下载文件时,我面临以下问题:

  • Chrome :文件已下载,但该文件未命名且没有文件扩展名
  • IE :文件甚至没有下载。

这是我的JS代码:

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();
   }
}

2 个答案:

答案 0 :(得分:2)

请参阅以下特定浏览器的修补程序:

function downloadFile(filename, csvContent) {
var blob = new Blob([csvContent]);
var needsClick = true;
var browser = "";
if ( window.webkitURL ) {
    browser = "CHROME";
    var link = document.createElement("a");
    link.setAttribute("href", "data:text/csv;charset=utf-8," + encodeURI(csvContent));
    link.setAttribute("target", "_blank");
    link.setAttribute("download", filename);
    link.click();
} else {
    if (document.createEvent) {
        browser = "FIREFOX";
        var link = document.createElement("a");
        link.setAttribute("href", encodeURI("data:text/csv;charset=utf-8," + csvContent));
        link.setAttribute("download", filename);
        var e = document.createEvent('MouseEvents');
        e.initEvent('click', true, true);
        needsClick = link.dispatchEvent(e);
    }
    if(needsClick) {
        if(window.navigator.msSaveBlob != undefined){
            browser = "IE";
            window.navigator.msSaveBlob(blob, filename);
        }
    }
}
console.log(browser); }

答案 1 :(得分:1)

您可以使用this question的建议答案解决此问题,至少对Chrome来说是这样。

但我不知道Internet Explorer或任何其他浏览器的答案。