gpt4 book ai didi

javascript - 创建 CSV 并使用 JS 打开,在 IE、Chrome 中不起作用

转载 作者:行者123 更新时间:2023-11-28 19:45:52 27 4
gpt4 key购买 nike

我通过提供文件名、逗号分隔的 header 和数据键值对象从 js 对象创建 CSV 文件。但是,当我去下载文件时,我面临以下问题:

  • Chrome:文件下载,但文件未命名且没有文件扩展名
  • IE:文件甚至无法下载。

这是我的 JS 代码:

function createCSV(filename, headers, data) {

var csvContent = "data:text/csv;charset=utf-8," + headers;
data.forEach(function(d, index) {

var dataString = "";
var i = 0;

for ( var key in d) {

if (d[key] == 'null')
dataString += '\"\"';
else
dataString += "\"=\"\"" + d[key] + "\"\"\"";

if (i < Object.keys(d).length - 1)
dataString += ",";

i++;
}

if (index < data.length)
csvContent += "\n";

csvContent += dataString;
});

var filename = filename + ".csv"

var link = document.createElement("a");
link.setAttribute("href", encodeURI(csvContent));
link.setAttribute("download", filename);
actuateLink(link);
}

function actuateLink(link)
{
var allowDefaultAction = true;

if (link.click)
{
link.click();
return;
}
else if (document.createEvent)
{
var e = document.createEvent('MouseEvents');
e.initEvent('click', true, true);
allowDefaultAction = link.dispatchEvent(e);
}

if (allowDefaultAction)
{
var f = document.createElement('form');
f.action = link.href;
document.body.appendChild(f);
f.submit();
}
}

最佳答案

请参阅下面针对特定浏览器的修复:

function downloadFile(filename, csvContent) {
var blob = new Blob([csvContent]);
var needsClick = true;
var browser = "";
if ( window.webkitURL ) {
browser = "CHROME";
var link = document.createElement("a");
link.setAttribute("href", "data:text/csv;charset=utf-8," + encodeURI(csvContent));
link.setAttribute("target", "_blank");
link.setAttribute("download", filename);
link.click();
} else {
if (document.createEvent) {
browser = "FIREFOX";
var link = document.createElement("a");
link.setAttribute("href", encodeURI("data:text/csv;charset=utf-8," + csvContent));
link.setAttribute("download", filename);
var e = document.createEvent('MouseEvents');
e.initEvent('click', true, true);
needsClick = link.dispatchEvent(e);
}
if(needsClick) {
if(window.navigator.msSaveBlob != undefined){
browser = "IE";
window.navigator.msSaveBlob(blob, filename);
}
}
}
console.log(browser); }

关于javascript - 创建 CSV 并使用 JS 打开,在 IE、Chrome 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24292710/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com