1、
npm install file-saver --save
npm install xlsx --save
2、在vue文件引入
import FileSaver from 'file-saver';
import XLSX from 'xlsx';
3、导出方法
一、导出已有表格
sureExport(){
/* generate workbook object from table */
let wb = XLSX.utils.table_to_book(document.querySelector('#exportTable'),{raw:true })
/* get binary string as output */
let wbout = XLSX.write(wb, {bookType:'xlsx', bookSST:true, type:'array'})
try {
FileSaver.saveAs(new Blob([wbout], {type:'application/octet-stream'}), '设施影响统计.xlsx')
}catch (e) {
if (typeof console !=='undefined') {
console.log(e, wbout)
}
}
return wbout
},
二、导出数据(未生成表格)来源(https://www.jianshu.com/p/81f208e257a8 vue 导出(下载)XLSX 表格 - 简书)
functiondownloadXlsxFile(dataArray:any,fields:any,filename:string){/**
* 表格数据 => dataArray=[{id:"1",name:"666",sex:"男"}]
* 表格数据的title => fields={id:"id",name:"名字",sex:"性别"}
* 表格名字 => filename
*/vardata=JSON.stringify(dataArray);varnewData=JSON.parse(data);newData.forEach((item:any)=>{if(item){for(letiinitem){if(fields.hasOwnProperty(i)){item[fields[i]]=item[i];}deleteitem[i];//删除原先的对象属性}}})letsheetName=filename//excel的文件名称letwb=XLSX.utils.book_new()//工作簿对象包含一SheetNames数组,以及一个表对象映射表名称到表对象。XLSX.utils.book_new实用函数创建一个新的工作簿对象。letws=XLSX.utils.json_to_sheet(newData,{header:Object.values(fields)})//将JS对象数组转换为工作表。wb.SheetNames.push(sheetName)wb.Sheets[sheetName]=wsconstdefaultCellStyle={font:{name:"Verdana",sz:13,color:"FF00FF88"},fill:{fgColor:{rgb:"FFFFAA00"}}};//设置表格的样式letwopts={bookType:'xlsx',bookSST:false,type:'binary',cellStyles:true,defaultCellStyle:defaultCellStyle,showGridLines:false}//写入的样式letwbout=XLSX.write(wb,wopts)letblob=newBlob([s2ab(wbout)],{type:'application/octet-stream'})fs.saveAs(blob,filename+'.xlsx')}functions2ab(s){if(typeofArrayBuffer!=='undefined'){varbuf=newArrayBuffer(s.length)varview=newUint8Array(buf)for(vari=0;i!=s.length;++i)view[i]=s.charCodeAt(i)&0xffreturnbuf}else{varbuf=newArray(s.length);for(vari=0;i!=s.length;++i)buf[i]=s.charCodeAt(i)&0xFF;returnbuf;}}