通过 Web API,下载 CSV 格式的 blob 文件以在 Excel 中打开。下面的代码适用于 Chrome 和 Firefox,但不适用于 IE 或 Edge。除了,当我添加如下所示的“window.open(url)”行时,它会在 Edge 中打开,但仍然不会在 IE 中打开(但有了这行额外的行,Chrome 会打开另一个不必要的选项卡,甚至不会工作,但文件仍然下载并打开)。希望得到有关如何使其在每个浏览器中正常工作的答案。还会在 IE 和 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。否则,它使用与您为任何其他浏览器发布的逻辑类似的逻辑。
关于javascript - 在 Excel 中下载并打开 CSV 适用于 Chrome 和 Firefox,但不适用于 IE 或 Edge,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49266846/