JS生成EXCEL(Chrome瀏覽器)
阿新 • • 發佈:2018-08-21
utf-8 aps 拷貝 ref offic data idt return 設置
直接使用js+Html生成excel文件,當前版本:chrome瀏覽器
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <style type="text/css"> 6 table{border-collapse: collapse; } 7 th, td{border: 1px solid #4d4d4d;padding: 5px; } 8 </style> 9 <script type="text/javascript" language="javascript"> 10 var idTmr; 11 function getExplorer() { 12 var explorer = window.navigator.userAgent ; 13 if(explorer.indexOf("Chrome") >= 0){ 14 return ‘Chrome‘; 15 }else{ 16 alert("非chrome瀏覽器"); 17 return false; 18 } 19 } 20 function method1(tableid) {//整個表格拷貝到EXCEL中 21 tableToExcel(‘tableId‘) 22 } 23 var tableToExcel = (function(tableId) { 24 //設置類型 25 var uri = ‘data:application/vnd.ms-excel;base64,‘, 26 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>{table}</table></body></html>‘, 27 //base64加密處理 28 base64 = function(s) { 29 return window.btoa(unescape(encodeURIComponent(s))) 30 }, 31 //格式化處理 32 format = function(s, c) { 33 return s.replace(/{(\w+)}/g, 34 function(m, p) { 35 return c[p]; 36 } 37 ) 38 }; 39 //自動執行 40 return function(tableId, name) { 41 var aLink=document.getElementById("dlink"); 42 var table = document.getElementById(tableId); 43 // 獲取表單的名字和表單查詢的內容 44 var ctx = {worksheet: name || ‘Worksheet‘, table: table.innerHTML}; 45 // format()函數:通過格式操作使任意類型的數據轉換成一個字符串 46 // base64():進行編碼 47 aLink.href = uri + base64(format(template, ctx)) 48 aLink.download="test.xls"; 49 aLink.click(); 50 } 51 })() 52 </script> 53 54 </head> 55 <body> 56 <table id="tableId"> 57 <tr> 58 <th></th> 59 <th>一</th> 60 <th>二</th> 61 <th>三</th> 62 <th>四</th> 63 </tr> 64 <tr> 65 <td>萬籟寂無聲</td> 66 <td>衾鐵棱棱近五更</td> 67 <td>香斷燈昏吟未穩</td> 68 <td>淒清</td> 69 <td>只有霜華伴月明</td> 70 </tr> 71 <tr> 72 <td>應是夜寒凝</td> 73 <td>惱得梅花睡不成</td> 74 <td>我念梅花花念我</td> 75 <td>關情</td> 76 <td>起看清冰滿玉瓶</td> 77 </tr> 78 </table> 79 <br/> 80 <a id="dlink" style="display: none;"></a> 81 <input type="button" value="導出EXCEL" onclick="method1(‘tableId‘)" /> 82 </body> 83 </html>
JS生成EXCEL(Chrome瀏覽器)