vue3,vue2导出表格中的数据,导出excel格式
引入npm包
"xlsx": "^0.18.5"
import * as XLSX from 'xlsx';
async function exportExcel() {
if (!itemsquan.value || itemsquan.value.length == 0) {
console.log("暂无数据可以导出 ")
return;
}
// 拷贝原数据
let tableitem = JSON.parse(JSON.stringify(itemsquan.value));
// 修改数据中的字段
await tableitem.forEach(async (it: any) => {
it.attachmentid1 = it.attachmentid1 > 0 ? '测试' : '测试2';
});
// 列名
let columnArr = [
'省份',
'城市',
];
//列对应的值
let keyArr = [
'province',
'city',
];
const columns = generateColumns(keyArr.length, keyArr, columnArr);
const res: string[][] = tableitem.map((it) => {
const arr: any = [];
columns.forEach((column) => {
arr.push(it[column.dataKey]);
});
return arr;
});
const titleList: string[] = [];
columns.forEach((column) => {
titleList.push(column.title);
});
res.unshift(titleList);
const workSheet = XLSX.utils.aoa_to_sheet(res);
const workBook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workBook, workSheet, '报表');
//设置导出名称(DateFormatPipe为自定义函数,可忽略)
let time = DateFormatPipe(new Date(), 'yyyy-MM-dd');
let name_ext = '查看_' + questionnaireName.value + '_' + time + '.xlsx';
XLSX.writeFile(workBook, name_ext);
}