html導出Excel方法

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

相關文章
相關標籤/搜索