在工作中,我们有时会遇到这样的需求,比如:要把页面的表格数据导出为Excel文件。在此记录下自己用的解决方法。代码如下:
function tableToExcel(data){ //要导出的数据,table表格字符串 var str = data; //Worksheet名 var worksheet = 'Sheet1' var uri = 'data:application/vnd.ms-excel;base64,'; //下载的表格模板数据 var template = `<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><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]--></head><body><table>${str}</table></body></html>`; //下载模板 window.location.href = uri + base64(template) } //输出base64编码 function base64(s) { return window.btoa(unescape(encodeURIComponent(s))) }