js export Excel table

js export Excel table

Direct code:

Red part: if there is a value such as "1 / 1" in the table data, it will be converted to the date "January 1" in the exported Excel, so the two sentences in red are added. If there is no such format in the return value, the red part can be left blank.

 1 //Excel download
 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             ;//Must be a Tag, otherwise the rename cannot be downloaded
41             dom.download = fName;
42             break;
43     }
44 }

Reference:

1. First of all, label a.

2. this: click a.

3. 'grid basic': id name of the table.

4. 'PON port occupancy statistical report': table name after Excel export

<a onClick="exportOffice(this,'grid-basic','PON Port occupancy statistics report')">export Excel</a>

 

Attached is the partial reference of conversion Red: https://www.cnblogs.com/zhangym118/p/6378469.html

Keywords: Javascript Excel xml

Added by jmaccs64 on Sun, 01 Dec 2019 14:15:02 +0200