js匯出Excel表格

小旺同學發表於2018-12-29

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

  

 

相關文章