html部分:
<a href="javascript:;" type="button" id="export">导出</a> <table id="tableExcel"> <thead> <tr> <th>姓名</th> <th>IQ</th> </tr> </thead> <tbody> <tr> <td>阿杜</td> <td>700</td> </tr> </tbody> </table>
js部分:
<script> $("#export").click(function () { tableToExcel("tableExcel", "export"); }) function tableToExcel(tableid,btnname) { var uri = 'data:application/vnd.ms-excel;base64,' , 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><meta charset="UTF-8"><!--[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>' , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) } , format = function (s, c) { return s.replace(/{(w+)}/g, function (m, p) { return c[p]; }) } //根据ID获取table表格HTML var table = document.getElementById(tableid); var ctx = { worksheet: 'Worksheet', table: table.innerHTML }; document.getElementById(btnname).href = uri + base64(format(template, ctx)); document.getElementById(btnname).download = '还阔以.xls'; }; </script>
我把document.getElementById(btnname)换成window.location.href有问题,具体原因还在研究
【改进版】
我不想使用a标签,我想使用button,那么怎么使用href属性呢,
实现代码如下,只需要修改两处:
<button id="export">导出</button> //改成按钮
然后:
var alink = document.createElement("a"); alink.href = uri + base64(format(template, ctx)); alink.download = '还阔以.xls'; alink.click();
这样的话,我直接新建一个element元素,然后将属性迁移到它上面