繁体   English   中英

下载并打开Excel中的CSV可以在Chrome和Firefox中使用,但不能在IE或Edge中使用

[英]Download and open CSV in Excel works in Chrome and Firefox but not IE or Edge

通过Web API,下载格式为CSV的Blob文件,以便在Excel中打开。 以下代码可在Chrome和Firefox中使用,但不适用于IE或Edge。 除外,当我添加如下所示的“ window.open(url)”行时,它将在Edge中打开,但仍不会在IE中打开(但是,使用此额外的行,Chrome随后会打开另一个不必要的标签,甚至不需要工作,但文件仍会下载并打开)。 希望找到有关如何在每个浏览器中正常运行的答案。 在IE和Edge中也收到“访问被拒绝”消息,但此消息不会阻止文件通过Edge加上我提到的额外行通过Edge下载和打开。

var fileName = 'MovieList.csv';
var a = document.createElement("a");
a.style = "display: none";
var blob = new Blob([data], { type: "octet/stream" });
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
window.open(url);
window.URL.revokeObjectURL(url);

IE总是很有趣! 我以前曾遇到过这个问题,所以回头看看我做了什么。 这是我的片段:

var blob = new Blob([csvFile], { 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);
    }
}

它查找IE 10+函数“ navigator.msSaveBlob”,如果找到该函数,则使用它来保存Blob。 否则,它将使用与您为其他任何浏览器发布的逻辑类似的逻辑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM