原文:How to export JavaScript array info to csv (on client side)? - Stack Overflow
假若有一个数组如下,我们想根据该数组生成一个 CSV 文件。
const rows = [
["name1", "city1", "some other info"],
["name2", "city2", "more info"]
];
代码如下:
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");
现在生产 CSV 文件的下载链接:
let encodedUri = encodeURI(csvContent);
我们会得到一个这样的链接:
'data:text/csv;charset=utf-8,name1,city1,some%20other%20info%0Aname2,city2,more%20info'
封装成函数,更便于使用:
function arrayToCsv(rows) {
let csvContent = "data:text/csv;charset=utf-8,";
rows.forEach(function(rowArray) {
let row = rowArray.join(",");
csvContent += row + "\r\n";
});
return encodeURI(csvContent);
}
我们再扩展一下,如果数组里面是对象,我们这样转成 CSV:
let items = [
{name: 'tom', age: 20},
{name: 'lily', age: 18}
]
function objectToArray(item) {
let content = [];
Object.keys(item).forEach(function(key) {
let value = item[key];
content.push(value);
})
return content;
}
function arrayToCsv(rows) {
let csvContent = "data:text/csv;charset=utf-8,";
rows.forEach(function(rowArray) {
let row = rowArray.join(",");
csvContent += row + "\r\n";
});
return encodeURI(csvContent);
}
arrayToCsv(items.map(objectToArray))
日常使用中,我们会发现上述方法如果导出中文信息,会导致 CSV 文件乱码,解决方法是添加 "\ufeff"
字符串。
function arrayToCsv(rows) {
let csvContent = "data:text/csv;charset=utf-8,\ufeff";
rows.forEach(function(rowArray) {
let row = rowArray.join(",");
csvContent += row + "\r\n";
});
return encodeURI(csvContent);
}
网友评论