手抄报 安全手抄报 手抄报内容 手抄报图片 英语手抄报 清明节手抄报 节约用水手抄报

如何使用js在浏览器上导出excel

时间:2024-10-23 13:21:12

1、首先,界面上要有一个html表格,该表格的内容作为导出用如<table border="1" id="dataT锾攒揉敫able"> <tr> <th>Month</th> <th>Savings</th> </tr> <tr> <td>January</td> <td>$100</td> </tr></table>

如何使用js在浏览器上导出excel

2、表格的内容非常简单

如何使用js在浏览器上导出excel

3、在js中添加这个函数var tableToExcel = (function() 辘腋粪梯{ 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><!--[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]; }) } return function(table, name) { if (!table.nodeType) table = document.getElementById(table); var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }; window.location.href = uri + base64(format(template, ctx)); }})();

如何使用js在浏览器上导出excel

4、函数tableToExcel 的第一个参数为table的dom元素或者table的id值,第二个参数是table内容所在的worksheet的名字比如tableToExcel(document.getElementById("dataTable"), "导出表格");

5、现在所有内容都准备好了

如何使用js在浏览器上导出excel

6、点击运行,成功导出了表格,把它下载下来

如何使用js在浏览器上导出excel

7、打开看看,发现内容是正确的

如何使用js在浏览器上导出excel
© 手抄报圈