web 数据保存为excel文件
直接上代码:
doExport():void {
const logData = [];//数据
const exportArr = [];
for(let i=0;i<this.logData.length;i++) {
const logType = '类型可多种';
const obj = {"序号":(i+1),"日志记录时间":this.logData[i].recordTime,"类型":logType,"用户所在组":this.logData[i].groupName ,"用户名":this.logData[i].userName,"登录IP":this.logData[i].loginIP,"内容":this.logData[i].text };
exportArr.push(obj);
}
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(exportArr);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
this.saveAsExcelFile(excelBuffer, '日志备份');
}
private saveAsExcelFile(buffer: any, fileName: string) {
const data: Blob = new Blob([buffer], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
});
const date = new Date();
const dateString = date.getFullYear()+""+(date.getMonth()+1)+""+date.getDate()+""+date.getHours()+""+date.getMinutes()+""+date.getSeconds();
FileSaver.saveAs(data, fileName + '_' + dateString + '.xlsx');
}
依赖的包:
npm install file-saver --save
npm install @types/file-save --save-dev
npm install xlsx --save