前端文件匯出封裝
阿新 • • 發佈:2021-12-17
首先引入外掛
importXLSXfrom'xlsx'
importFileSaverfrom'file-saver'
封裝匯出的方法tableid代表的是匯出頁面表格的id;sheetName匯出檔案的名稱;css匯出檔案的樣式
exportfunctiontableToExcel(tableid,sheetName,css){
varuri='data:application/vnd.ms-excel;base64,';
vartemplate='<htmlxmlns:o="urn:schemas-microsoft-com:office:office"xmlns:x="urn:schemas-microsoft-com:office:excel"'+
'xmlns="http://www.w3.org/TR/REC-html40"><head><!--[ifgtemso9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>'
+'<x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets>'
+'</x:ExcelWorkbook></xml><![endif]-->'+
'<styletype="text/css">'+css+
'</style>'+
'</head><body><tableclass="excelTable">{table}</table></body></html>';
if(!tableid.nodeType)tableid=document.getElementById(tableid);
varctx={worksheet:sheetName||'Worksheet',table:tableid.innerHTML};
leturl=uri+base64(format(template,ctx));
openDownloadXLSXDialog(url,sheetName)
}
建立dom節點點選匯出,匯出完畢銷燬
functionopenDownloadXLSXDialog(url,saveName){
if(typeofurl=='object'&&urlinstanceofBlob){
url=URL.createObjectURL(url);
}
varaLink=document.createElement('a');
aLink.href=url;
aLink.download=saveName||'';
varevent;
if(window.MouseEvent){
event=newMouseEvent('click');
}
else{
event=document.createEvent('MouseEvents');
event.initMouseEvent('click',true,false,window,0,0,0,0,0,false,false,false,false,0,null);
}
aLink.dispatchEvent(event);
}