1. 网页另存为:重命名为 .xls便可html
2. <a>标签的download功能把href指向的文档下载,可在download属性中重命名为.xls浏览器
<a href="<!--要下载的html的URL-->" download="重命名.xls">导出到Excel</a>
3. IE的作法:app
<button id="btn">html转Excel</button> <script> var btn = document.getElementById('btn'); btn.onclick = function () { var OW = window.open('', "_blank", ""); OW.document.open(); OW.document.write('这是测试页面,经过另存为把html文件转成Excel'); OW.document.execCommand("saveAs", false, '重命名.xls');//执行另存为,IE6,IE7,IE8有效 OW.close(); }; </script>
4. 非IE的其余大部分浏览器的作法测试
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script> function toExcel(htmlBody) { var uri = 'data:application/vnd.ms-excel;base64,'; var htmlStart = '<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>'; var htmlEend = '</body></html>'; var template = htmlStart + htmlBody + htmlEend; var forExport = document.getElementById('forExport'); forExport.href = uri + window.btoa(unescape(encodeURIComponent(template))); forExport.click(); // window.location.href = uri + base64(template); } window.onload = function () { var btn = document.getElementById('btn'); btn.onclick = function () { var htmlBody = '<table><tr><td colspan="2">111</td><td>222</td></tr><tr><td>111</td><td>222</td><td>333</td></tr></table>'; toExcel(htmlBody); }; }; </script> </head> <body> <a id="forExport" style="visibility: hidden" href="#" download="数据导出.xls"></a> <button id="btn">html导出到Excel</button> </body> </html>
5.注意: 转换时遇到table中的一个单元格里有换行符<br/>则在Excel里会变成两个单元格。spa