Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在Excel中下载并打开CSV可在Chrome和Firefox中使用,但不能在IE或Edge中使用_Javascript - Fatal编程技术网

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

Javascript 在Excel中下载并打开CSV可在Chrome和Firefox中使用,但不能在IE或Edge中使用,javascript,Javascript,通过Web API,下载格式为CSV的blob文件以在Excel中打开。下面的代码适用于Chrome和Firefox,但不适用于IE或Edge。除此之外,当我添加下面显示的“window.open(url)”行时,它会在Edge中打开,但仍然不是IE(但有了这一额外的行,Chrome会打开另一个不必要的、甚至不起作用的选项卡,但文件仍会下载并打开)。希望找到如何在这些浏览器中正确工作的答案。在IE和Edge中也会收到一条“访问被拒绝”消息,但这条消息不会阻止文件通过Edge下载和打开,因为我提到

通过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);

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

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

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

太棒了!谢谢在IE和Edge中都能完美地工作!