简体   繁体   中英

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. Code below works in Chrome and Firefox but not IE or 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). 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.

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! 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. Otherwise, it uses similar logic to what you posted for any other browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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