我正在尝试将具有多行(来自服务器端)的字符串写入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();
}
Run Code Online (Sandbox Code Playgroud)
在下载的csv文件中,所有数据将在单行a,b,c,d1,2,3,4中.谁能告诉我如何解决这个问题?提前致谢!
尝试这样做
a.href = 'data:text/csv;charset=utf-8;base64,' + window.btoa(csvcontent);
它将数据转换为base64,正确编码新行字符.为什么它不能用你的方法我真的不确定.一个警告是该btoa功能在旧浏览器中不起作用查看此问题以获取更多信息如何在JavaScript中将字符串编码为Base64?
| 归档时间: |
|
| 查看次数: |
3107 次 |
| 最近记录: |