2018/10/19--Javascript导出json数据为csv格式
lq920320 opened this issue · comments
在页面中如何将table中的json数据导出为csv文件呢?下面一个方法即可搞定:
csvExport: function(jsonData) {
const replacer = (key, value) => (value === null ? "" : value);
const header = Object.keys(jsonData[0]);
var csv = jsonData.map(row =>
header
.map(fieldName => JSON.stringify(row[fieldName], replacer))
.join(",")
);
csv.unshift(header.join(","));
csv = csv.join("\r\n");
csv = "data:text/csv;charset=utf-8,\uFEFF" + csv;
console.log(csv);
const link = document.createElement("a");
link.href = encodeURI(csv);
link.download = `filename.csv`;
document.body.appendChild(link); // Required for FF
link.click(); // This will download the data file named 'my_data.csv'.
document.body.removeChild(link); // Required for FF
}