简体   繁体   English

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

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

Via Web API, download a blob file formatted as CSV to open in Excel. 通过Web API,下载格式为CSV的Blob文件,以便在Excel中打开。 Code below works in Chrome and Firefox but not IE or Edge. 以下代码可在Chrome和Firefox中使用,但不适用于IE或Edge。 Except, when I add the line "window.open(url)" which is shown below, it then opens in Edge but still not IE (but with this extra line Chrome then opens another tab that isn't necessary and doesn't even work but the file still downloads and opens). 除外,当我添加如下所示的“ window.open(url)”行时,它将在Edge中打开,但仍不会在IE中打开(但是,使用此额外的行,Chrome随后会打开另一个不必要的标签,甚至不需要工作,但文件仍会下载并打开)。 Hoping for answers on how to get this to work correctly in each of these browsers. 希望找到有关如何在每个浏览器中正常运行的答案。 Also get an 'Access is denied' message in IE and Edge but this message doesn't stop the file from downloading and opening via Edge with the extra line I mentioned. 在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 is always fun! IE总是很有趣! I had run into this issue previously so I looked back to see what I'd done. 我以前曾遇到过这个问题,所以回头看看我做了什么。 Here's the snippet I have: 这是我的片段:

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

It looks for the IE 10+ function 'navigator.msSaveBlob' and if found, uses that to save the blob. 它查找IE 10+函数“ navigator.msSaveBlob”,如果找到该函数,则使用它来保存Blob。 Otherwise, it uses similar logic to what you posted for any other browser. 否则,它将使用与您为其他任何浏览器发布的逻辑类似的逻辑。

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

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