安装
npm install file-saver
npm install xlsx
导入
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
//获取数据
exp() {
//表头
let exportcolums = [
{ title: '时间', index: 'time' },
{ title: 'radii', index: 'radii' },
{ title: 'force', index: 'force' },
];
let worksheet: XLSX.WorkSheet;
if (this.infoList.length!>0) {
//调用导出数据的方法
this.downloaddata(this.infoList, exportcolums, worksheet)
}
else {
console.log("导出失败")
}
}
downloaddata(scoredata, exportcolums, worksheet) {
//设置excel表的单元格宽度
var long = {
'001': [{ wch: 30 }, { wch: 15 }, { wch:15 }, { wch: 20 }, { wch: 30 }, { wch: 20 }, { wch: 30 }, { wch: 10 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 },
{ wch: 10 }, { wch: 15 }, { wch: 15 }, { wch: 25 }, { wch: 15 }, { wch: 15 }, { wch: 15 }]
}
//设置excel表第一行的高度
var row = {
'001': [{ hpt: 30 }]
}
console.log("导出",exportcolums)
if (scoredata.length) {
//处理数据
scoredata.forEach((element) => {
for (var key in element) {
let has = false;
for (var item of exportcolums) {
if (item.index == key) {
has = true;
}
}
}
})
worksheet = XLSX.utils.json_to_sheet(scoredata);
let header = []
//把excel表头的英文字段转化为中文字段
for (let i = Number('A'.charCodeAt(0)); i <= Number('V'.charCodeAt(0)); i++) {
header.push(String.fromCharCode(i) + '1')
}
//设置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');
}
参考:https://blog.csdn.net/qq_41093493/article/details/110520938