HTML中的table導出為Excel文件


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <a id="dlink" style="display:none;"></a>
    <input id="button" type="button" value="Export to Excel">
    <table id="tables">
        <caption>表格轉excel</caption>
        <!--可以生成表格的標題-->
        <thead>
            <tr>
                <th>功能</th>
                <th>功能描述</th>
                <th>參數取值范圍</th>
                <th title="ESC取消保存,Enter保存">取值</th>
            </tr>
        </thead>
        <tbody>
            <tr index="0">
                <td>網絡圖標是否顯示</td>
                <td>根據用戶需求適配是否顯示網絡i圖標 開啟:在主圖及導航界面顯示網絡圖標 關閉:不顯示網絡圖標
                </td>
                <td>true:開啟false:關閉</td>
            </tr>
            <tr index="1">
                <td>wifi未連接蒙層提醒</td>
                <td>為了引導用戶聯網,wifi未連接的情況下,進行強提醒。</td>
                <td>true:開啟false:關閉</td>
            </tr>
            <tr index="2">
                <td>衛星界面是否顯示車速值</td>
                <td>可在查看衛星的詳情界面配置是否顯示車速值</td>
                <td>true:開啟false:關閉</td>
            </tr>
        </tbody>
    </table>
    <script type="text/javascript">
    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, filename) {
            if (!table.nodeType) table = document.getElementById(table);
            console.log(table.innerHTML)
            var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }//此時的innerHTML數據可以自己自定義 比如json轉化 只要值要數據符合即可

            document.getElementById("dlink").href = uri + base64(format(template, ctx));
            document.getElementById("dlink").download = filename;
            document.getElementById("dlink").click();
        }
    });

    var id = "tables",
        worksheetName = 'sheet',
        workName = "demo.xls";

    document.getElementById('button').onclick = function() {
        var download = tableToExcel();
        download(id, worksheetName, workName)
    };
    </script>
</body>

</html>

 這種轉換沒有如下鏈接轉換的好, 詳情


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM