直接使用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>