首页 > 解决方案 > IE11下javascript生成CSV文件

问题描述

我阅读了大量样本以从数据中生成 csv 文件并将其推送到下载以导出它。

 let csvContent = '';
                $.each(msg.d.LstObj[0], function (key, element) { csvContent += (csvContent === '' ? '' : ',') + key; });
                csvContent += "\n";
                msg.d.LstObj.forEach(function (rowArray) {
                    var row = '';
                    $.each(rowArray, function (key, element) { row += (row === '' ? '' : ',') + element; });
                    csvContent += row + "\n";
                });
                var hiddenElement = document.createElement('a');
                hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvContent);
                hiddenElement.target = '_blank';
                hiddenElement.download = 'people.csv';
                hiddenElement.click();

在 Chrome FF 下:好的 在 IE11 下:没有下载只是一条消息问我:

voulez vous autoriser ce 站点 web à ouvrir une 应用程序

只有一个选择橱窗商店......有人有想法吗???我把我的代码放在“site de confiance”中......

标签: jqueryexport-to-csv

解决方案


这是我用来满足所有浏览器的块,包括 IE 11,它对我来说非常有用:

if (window.navigator.msSaveBlob) {
    //Internet Explorer
    window.navigator.msSaveBlob(new Blob([result]), csvFileName);
} else if (window.webkitURL != null) {
    //Google Chrome and Mozilla Firefox
    var a = document.createElement("a");
    result = encodeURIComponent(result);
    a.href = "data:application/csv;charset=UTF-8," + result;
    a.download = csvFileName;
    a.click();
} else if (navigator.appName === "Microsoft Internet Explorer") {
    //Internet Explorer 8 and 9
    var oWin = window.open();
    oWin.document.write("sep=,\r\n" + result);
    oWin.document.close();
    oWin.document.execCommand("SaveAs", true, csvFileName);
    oWin.close();
} else {
    //Everything Else
    window.open(result);
}

推荐阅读