js导出Excel表格
直接上代码:
红色部分:如果表格数据中有“1/1”这样的值,会在导出的Excel中转化为日期“1月1日”,所以才加上了红色那两句。如果返回值中没有这样的格式,红色部分可以不写。
1 //Excel下载 2 function base64(content) { 3 return window.btoa(unescape(encodeURIComponent(content))); 4 } 5 function exportOffice(dom, tableID, fName) { 6 var type = 'excel'; 7 var table = document.getElementById(tableID); 8 var excelContent = table.innerHTML; 9 var ddd="<td style=\"mso-number-format:'\\@';\">"; 10 var result=((excelContent).toString()).replace(/<td(.*?)>/g,ddd); 11 console.log(result); 12 var excelFile = "<html xmlns:v='urn:schemas-microsoft-com:vml' xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:" + type + "' xmlns='http://www.w3.org/TR/REC-html40'>"; 13 excelFile += "<head>"; 14 excelFile += "<meta http-equiv=Content-Type; content=text/html;charset=UTF-8>"; 15 excelFile += "<!--[if gte mso 9]>"; 16 excelFile += "<xml>"; 17 excelFile += "<x:ExcelWorkbook>"; 18 excelFile += "<x:ExcelWorksheets>"; 19 excelFile += "<x:ExcelWorksheet>"; 20 excelFile += "<x:Name>"; 21 excelFile += "{worksheet}"; 22 excelFile += "</x:Name>"; 23 excelFile += "<x:WorksheetOptions>"; 24 excelFile += "<x:DisplayGridlines/>"; 25 excelFile += "</x:WorksheetOptions>"; 26 excelFile += "</x:ExcelWorksheet>"; 27 excelFile += "</x:ExcelWorksheets>"; 28 excelFile += "</x:ExcelWorkbook>"; 29 excelFile += "</xml>"; 30 excelFile += "<![endif]-->"; 31 excelFile += "</head>"; 32 excelFile += "<body><table>"; 33 excelFile += result; 34 excelFile += "</table></body>"; 35 excelFile += "</html>"; 36 var base64data = "base64," + base64(excelFile); 37 switch (type) { 38 case 'excel': 39 dom.href = 'data:application/vnd.ms-' + type + ';' + base64data; 40 ;//必须是a标签,否则无法下载改名 41 dom.download = fName; 42 break; 43 } 44 }
引用:
1、首先得是a标签。
2、this:指向a的点击。
3、'grid-basic':表格的id名。
4、'统计报表':导出Excel后的表格名
<a onClick="exportOffice(this,'grid-basic','统计报表')">导出Excel</a>
附上转换红色部分参考文献:https://www.cnblogs.com/zhangym118/p/6378469.html
来源:https://www.cnblogs.com/nelsonlei/p/10197086.html