1,导出excal,下两个插件
cnpm i file-saver --save cnpm i xlsx --save
2,新建exportExcel.js文件
/* eslint-disable */import{saveAs}from'file-saver'import*asXLSXfrom'xlsx'functiongenerateArray(table){varout=[];varrows=table.querySelectorAll('tr');varranges=[];for(varR=0;R<rows.length;++R){varoutRow=[];varrow=rows[R];varcolumns=row.querySelectorAll('td');for(varC=0;C<columns.length;++C){varcell=columns[C];varcolspan=cell.getAttribute('colspan');varrowspan=cell.getAttribute('rowspan');varcellValue=cell.innerText;if(cellValue!==""&&cellValue==+cellValue)cellValue=+cellValue;//Skip rangesranges.forEach(function(range){if(R>=range.s.r&&R<=range.e.r&&outRow.length>=range.s.c&&outRow.length<=range.e.c){for(vari=0;i<=range.e.c-range.s.c;++i)outRow.push(null);}});//Handle Row Spanif(rowspan||colspan){rowspan=rowspan||1;colspan=colspan||1;ranges.push({s:{r:R,c:outRow.length},e:{r:R+rowspan-1,c:outRow.length+colspan-1}});};//Handle ValueoutRow.push(cellValue!==""?cellValue:null);//Handle Colspanif(colspan)for(vark=0;k<colspan-1;++k)outRow.push(null);}out.push(outRow);}return[out,ranges];};functiondatenum(v,date1904){if(date1904)v+=1462;varepoch=Date.parse(v);return(epoch-newDate(Date.UTC(1899,11,30)))/(24*60*60*1000);}functionsheet_from_array_of_arrays(data,opts){varws={};varrange={s:{c:10000000,r:10000000},e:{c:0,r:0}};for(varR=0;R!=data.length;++R){for(varC=0;C!=data[R].length;++C){if(range.s.r>R)range.s.r=R;if(range.s.c>C)range.s.c=C;if(range.e.r<R)range.e.r=R;if(range.e.c<C)range.e.c=C;varcell={v:data[R][C]};if(cell.v==null)continue;varcell_ref=XLSX.utils.encode_cell({c:C,r:R});if(typeofcell.v==='number')cell.t='n';elseif(typeofcell.v==='boolean')cell.t='b';elseif(cell.vinstanceofDate){cell.t='n';cell.z=XLSX.SSF._table[14];cell.v=datenum(cell.v);}elsecell.t='s';ws[cell_ref]=cell;}}if(range.s.c<10000000)ws['!ref']=XLSX.utils.encode_range(range);returnws;}functionWorkbook(){if(!(thisinstanceofWorkbook))returnnewWorkbook();this.SheetNames=[];this.Sheets={};}functions2ab(s){varbuf=newArrayBuffer(s.length);varview=newUint8Array(buf);for(vari=0;i!=s.length;++i)view[i]=s.charCodeAt(i)&0xFF;returnbuf;}exportfunctionexport_table_to_excel(id){vartheTable=document.getElementById(id);varoo=generateArray(theTable);varranges=oo[1];/* original data */vardata=oo[0];varws_name="SheetJS";varwb=newWorkbook(),ws=sheet_from_array_of_arrays(data);/* add ranges to worksheet */// ws['!cols'] = ['apple', 'banan'];ws['!merges']=ranges;/* add worksheet to workbook */wb.SheetNames.push(ws_name);wb.Sheets[ws_name]=ws;varwbout=XLSX.write(wb,{bookType:'xlsx',bookSST:false,type:'binary'});saveAs(newBlob([s2ab(wbout)],{type:"application/octet-stream"}),"test.xlsx")}exportfunctionexport_json_to_excel({multiHeader=[],header,data,filename,merges=[],autoWidth=true,bookType='xlsx'}={}){/* original data */filename=filename||'excel-list'data=[...data]data.unshift(header);for(leti=multiHeader.length-1;i>-1;i--){data.unshift(multiHeader[i])}varws_name="SheetJS";varwb=newWorkbook(),ws=sheet_from_array_of_arrays(data);if(merges.length>0){if(!ws['!merges'])ws['!merges']=[];merges.forEach(item=>{ws['!merges'].push(XLSX.utils.decode_range(item))})}if(autoWidth){/*设置worksheet每列的最大宽度*/constcolWidth=data.map(row=>row.map(val=>{/*先判断是否为null/undefined*/if(val==null){return{'wch':10};}/*再判断是否为中文*/elseif(val.toString().charCodeAt(0)>255){return{'wch':val.toString().length*2};}else{return{'wch':val.toString().length};}}))/*以第一行为初始值*/letresult=colWidth[0];for(leti=1;i<colWidth.length;i++){for(letj=0;j<colWidth[i].length;j++){if(result[j]['wch']<colWidth[i][j]['wch']){result[j]['wch']=colWidth[i][j]['wch'];}}}ws['!cols']=result;}/* add worksheet to workbook */wb.SheetNames.push(ws_name);wb.Sheets[ws_name]=ws;varwbout=XLSX.write(wb,{bookType:bookType,bookSST:false,type:'binary'});saveAs(newBlob([s2ab(wbout)],{type:"application/octet-stream"}),`${filename}.${bookType}`);}functionformatJson(jsonSource,jsonFillter){returnjsonSource.map(v=>jsonFillter.map(j=>{returnv[j]}))}exportfunctionexport_json_to_excel2(th,jsonSource,jsonFillter,name){constdata=formatJson(jsonSource,jsonFillter)export_json_to_excel({header:th,data,filename:name})}
3,在需要导出的页面里面写
// 导出ExcelexportExcel(){import('@/util/exportExcel').then((excel)=>{consttHeader=['区域','机构','设备']constfilterVal=['areaName','organizationName','deviceName']excel.export_json_to_excel2(tHeader,表格数组,filterVal,'xxx详细信息')})}
导出PDF
1,导出PDF,下两个插件
cnpm i html2canvas --save cnpm i jspdf --save
2,新建exportPdf.js
// 导出页面为PDF格式importhtml2Canvasfrom'html2canvas'importJsPDFfrom'jspdf'exportdefault{install(Vue){Vue.prototype.getPdf=function(){vartitle=this.htmlTitlehtml2Canvas(document.querySelector('#pdfDom'),{allowTaint:true}).then(function(canvas){letcontentWidth=canvas.widthletcontentHeight=canvas.heightletpageHeight=contentWidth/592.28*841.89letleftHeight=contentHeightletposition=0letimgWidth=595.28letimgHeight=592.28/contentWidth*contentHeightletpageData=canvas.toDataURL('image/jpeg',1.0)letPDF=newJsPDF('','pt','a4')if(leftHeight<pageHeight){PDF.addImage(pageData,'JPEG',0,0,imgWidth,imgHeight)}else{while(leftHeight>0){PDF.addImage(pageData,'JPEG',0,position,imgWidth,imgHeight)leftHeight-=pageHeight position-=841.89if(leftHeight>0){PDF.addPage()}}}PDF.save(title+'.pdf')})}}}
3,main.js挂载
importexportPdffrom'@/util/exportPdf'Vue.use(exportPdf)
4,在需要导出的页面使用
<el-table id="pdfDom":data="tableData">...</el-table>...data(){return{htmlTitle:'',// 导出的文件名}},methods:{// 导出pdfexportPdf(){this.htmlTitle='xxx详细信息'this.getPdf()}}
以上就是ue项目表格导出为Excel和PDF的方法了
作者:最进
链接:https://www.jianshu.com/p/01054dbc36a6
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。