实现思路
使用json2csv将后台json数据转化为csv格式数据
创建一个a标签,设置href和download属性
触发a标签的点击事件实现下载
移除a标签
相关代码:
import json2csv from 'json2csv'
exportCsv () {
try {
let columns = this.$refs.table.$children.filter(t => t.prop != null)
const fields = columns.map(t => t.prop)
const fieldNames = columns.map(t => t.label)
var link = document.createElement("a");
var result = json2csv({ data: data, fields: fields, fieldNames: fieldNames });
var csvContent = "data:text/csv;charset=GBK,\uFEFF" + result;
var encodedUri = encodeURI(csvContent);
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".
document.body.removeChild(link); // Required for FF
} catch (err) {
// Errors are thrown for bad options, or if the data is empty and no fields are provided.
// Be sure to provide fields if it is possible that your data array will be empty.
console.error(err);
}
}
调用以上方法就实现了csv文件的导出,但是笔者在开发时遇到了一个小坑,当数据量较大时以上导出代码会失效,并且catch不到err,Chrome执行下载不成功:
这是因为url有最大长度限制,encodeURI是会把字符串转化为url,超出限制长度部分数据丢失导致下载失败,为此我采用创建Blob(二进制大对象)的方式来存放缓存数据,具体代码如下:
var blob = new Blob(["\ufeff" + result], {type: 'text/csv'}); //解决大文件下载失败
link.setAttribute("href", URL.createObjectURL(blob));
Chrome 执行下载成功: