如何将JavaScript数组信息导出到csv(在客户端)?

我知道有很多这种性质的问题,但是我需要使用JavaScript来完成。我正在使用Dojo 1.8并将所有属性信息都放在数组中,如下所示:

[["name1", "city_name1", ...]["name2", "city_name2", ...]]

知道如何将其导出到CSV客户端吗?

Pro梅2020/03/12 18:32:31

I would recommend using a library like PapaParse: https://github.com/mholt/PapaParse

The accepted answer currently has multiple issues including:

  • it fails if the data contains a comma
  • it fails if the data contains a linebreak
  • it (kind of) fails if the data contains a quotation mark
小小Sam小哥2020/03/12 18:32:30

这里有很多将数据转换为CSV的自带解决方案,但是几乎所有这些解决方案在正确格式化数据类型方面都会有各种警告,而不会引起Excel或类似问题。

Why not use something proven: Papa Parse

Papa.unparse(data[, config])

Then just combine this with one of the local download solutions here eg. the one by @ArneHB looks good.

乐古一2020/03/12 18:32:30

您可以使用下面的代码使用Javascript将数组导出到CSV文件。

这也处理特殊字符部分

var arrayContent = [["Séjour 1, é,í,ú,ü,ű"],["Séjour 2, é,í,ú,ü,ű"]];
var csvContent = arrayContent.join("\n");
var link = window.document.createElement("a");
link.setAttribute("href", "data:text/csv;charset=utf-8,%EF%BB%BF" + encodeURI(csvContent));
link.setAttribute("download", "upload_data.csv");
link.click(); 

是工作jsfiddle的链接

阳光猿2020/03/12 18:32:30

@Default的解决方案在Chrome上运行完美(非常感谢!),但是IE出现问题。

这是一个解决方案(适用于IE10):

var csvContent=data; //here we load our csv data 
var blob = new Blob([csvContent],{
    type: "text/csv;charset=utf-8;"
});

navigator.msSaveBlob(blob, "filename.csv")
猴子JinJin2020/03/12 18:32:30

您可以使用本机JavaScript执行此操作。您必须这样将数据解析为正确的CSV格式(假设您正在使用问题中所描述的数组数组):

const rows = [
    ["name1", "city1", "some other info"],
    ["name2", "city2", "more info"]
];

let csvContent = "data:text/csv;charset=utf-8,";

rows.forEach(function(rowArray) {
    let row = rowArray.join(",");
    csvContent += row + "\r\n";
});

或更短的方法(使用箭头功能):

const rows = [
    ["name1", "city1", "some other info"],
    ["name2", "city2", "more info"]
];

let csvContent = "data:text/csv;charset=utf-8," 
    + rows.map(e => e.join(",")).join("\n");

然后,您可以使用JavaScript window.openencodeURI函数下载CSV文件,如下所示:

var encodedUri = encodeURI(csvContent);
window.open(encodedUri);

编辑:

如果要给文件指定一个特定的名称,则必须做一些不同的事情,因为不支持使用window.open方法访问数据URI 为了实现这一点,您可以创建一个隐藏的<a>DOM节点并按download如下所示设置其属性:

var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for FF

link.click(); // This will download the data file named "my_data.csv".