安装模块
npm install file-saver --save
npm install xlsx --save
导入模块
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
获取数据
//获取数据
exportExcel() {
// 首先调接口获取需要导出的数据
let params = {
"userId":localStorage.getItem('userid'),
"organizationType":this.currentSearchOrganizationType,
"assessmentYear":'2021',
"page":1,
"pageSize":10000,
"organizationName":this.currentOrganizationName,
"type":this.labelTypes,
"status":this.isParticipateStatistics
}
this.service.searchAnnualBonusList(params).subscribe((res:any)=>{
this.isShowSpin = false;
if (res.code != 200) {
this.service.getReturnCode(res.code,res.message);
return;
}
// 获取数据
this.excelDataList = res.data.rows;
//title 表示每列的名,index对应的数组对象中的属性名
let exportcolums = [
{ title: '序号', index: 'organizationName' },
{ title: '姓名', index: 'oneTimeBonus'},
{ title: '性别', index: 'oneTimeBonusPeople' },
{ title: '身份证号', index: 'meritsPayMoney' },
{ title: '总数', index: 'meritsPayAverage' },
];
let worksheet: XLSX.WorkSheet;
if (this.excelDataList.length>0) {
//调用导出数据的方法
this.downloaddata(this.excelDataList, exportcolums, worksheet)
}
else {
this.toastr.error('暂无数据,无法导出','错误')
}
})
}
downloaddata(scoredata, exportcolums, worksheet) {
//设置excel表的单元格宽度
var long = {
'001': [{ wch: 30}, { wch: 100 }, { wch:80 }, { wch: 40 }, { wch: 40 }]
}
//设置excel表第一行的高度
var row = {
'001': [{ hpt: 30 }]
}
console.log("导出",exportcolums)
if (scoredata.length) {
//处理数据 更改每一列的列名
let list = []
list = scoredata.map(item=>{
const obj = {}
exportcolums.forEach(ele=>{
obj[ele.title] = item[ele.index]
})
return obj
})
worksheet = XLSX.utils.json_to_sheet(list);
//设置excel表的单元格宽度和表头高度
worksheet['!cols'] = long['001'];
worksheet['!rows'] = row['001']
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
//保存excel表
this.saveAsExcelFile(excelBuffer, '专项统计表');
}
else {
console.log("没有数据")
}
}
saveAsExcelFile(buffer: any, fileName: string) {
const data: Blob = new Blob([buffer], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
});
FileSaver.saveAs(data, fileName + '.xlsx');
}