之前在工作的时候,有个需求是将查询出来的列表下载到本地,那么这个方法也就产生:
以下是代码片段:
No.1
exportList() {
for (const dt of this.list) {
dt.backType = this.transform(dt.backType, this.backTypeList, '|')
dt.backStatus = this.transform(dt.backStatus, this.backStatusList, '|')
}
if (!this.list || this.list.length === 0) {
this.msgs = [{ severity: 'error', summary: '提示', detail: '导出数据为空!' }];
return;
}
// 这个list的功能是将查询出来的结果加字段映射到excel中
const list = [
{
'sheetName': '客户查询结果表',
// ‘xuHao’这个字段其实也可以循环数组得道的
'sheetkeylist': [
'xuHao',
'custNo'
],
'sheetheadlist': [
'序号', '客户编号'
],
'sheetlist': this.list // 需要遍历的数组
}
]
// 调用文件下载的方法
this.commfunc.exportXLSX(list, '客户查询结果表');
}
以下这部分主要是对查询出来的数据部分字段进行码值的翻译
for (const dt of this.list) {
dt.backType = this.transform(dt.backType, this.backTypeList, '|')
dt.backStatus = this.transform(dt.backStatus, this.backStatusList, '|')
}
No.2
下面是核心代码:实现下载的核心功能
exportXLSX(list, excelName) {
const wb: XLSX.WorkBook = XLSX.utils.book_new();
for (const listbean of list) {
const exportList = [];
for (const sheetbean of listbean.sheetlist) {
const objlist = [];
for (const objvalue of listbean.sheetkeylist) {
objlist.push(sheetbean[objvalue]);
}
exportList.push(objlist)
}
const headlist = [];
for (const sheethead of listbean.sheetheadlist) {
headlist.push(sheethead);
}
exportList.unshift(headlist);
const ws: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(exportList);
XLSX.utils.book_append_sheet(wb, ws, listbean.sheetName);
}
console.log(wb);
XLSX.writeFile(wb, excelName + '.xlsx' || '导出数据.xlsx');
}
OK!不过,后来公司就改成前端直接从服务器拉文件了,虚浮~~~