html导出Excel方法

1. 网页另存为:重命名为 .xls即可

2. <a>标签的download功能把href指向的文档下载,可在download属性中重命名为.xls

<a href="<!--要下载的html的URL-->" download="重命名.xls">导出到Excel</a>

3. IE的做法:

<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里会变成两个单元格。

转载于:https://my.oschina.net/u/3697586/blog/1576491

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值