gpt4 book ai didi

Javascript:将多行字符串写入csv文件以供下载

转载 作者:行者123 更新时间:2023-12-03 12:51:24 25 4
gpt4 key购买 nike

我正在尝试将多行字符串(来自服务器端)写入一个 csv 文件,供用户在浏览器中下载。但是,使用我的代码,我只能在一行中获取包含所有数据的 csv 文件。这是我的代码:

function getReport(){
var report = "a,b,c,d;1,2,3,4;";
//console.log(report);
var csvcontent="";
while (report.indexOf(";")!=-1)
{
csvcontent=csvcontent+ report.substring(0,report.indexOf(";"))+"\n";
report=report.substring(report.indexOf(";")+1);
}

console.log(csvcontent);
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + csvcontent;
a.target = '_blank';
a.download = 'myFile.csv';
document.body.appendChild(a);
//console.log("ok");
a.click();
}

在下载的 csv 文件中,所有数据都在一行 a,b,c,d1,2,3,4 中。谁能告诉我如何解决这个问题?提前致谢!

最佳答案

试试这个
a.href = 'data:text/csv;charset=utf-8;base64,' + window.btoa(csvcontent);
它将数据转换为 base64,从而正确编码新行字符。为什么它在您的方法中不起作用我真的不确定。一个警告是 btoa 函数在旧版浏览器中不起作用查看此问题以获取更多信息 How can you encode a string to Base64 in JavaScript?

关于Javascript:将多行字符串写入csv文件以供下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23667074/

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