簡體   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