前端JS腳本將網頁表格導出為Excel


話不多說,上代碼!

<!DOCTYPE>
<html>
    <head>
        <title>Excel Test</title>
    </head>
    
    <body>
        <div style="width:100%;padding:40px;">
            Excel Test
        </div>
        <table id="excel">
            <tr>
                <td>Name</td>
                <td>Age</td>
                <td>Gender</td>
            </tr>
            <tr>
                <td>Young</td>
                <td>24</td>
                <td>Male</td>
            </tr>
            <tr>
                <td>Even</td>
                <td>23</td>
                <td>Female</td>
            </tr>
            <tr>
                <td>Leon</td>
                <td>25</td>
                <td>Male</td>
            </tr>
        </table>
    </body>
    <div style="width:200px;margin:auto;text-align:center;">
        <button onclick="ok()">導出</button>
    </div>
    
    <script>
    var ok = (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) {
            var tables = document.getElementById('excel');
            var ctx = { worksheet: name || 'Worksheet', table: tables.innerHTML }
            window.location.href = uri + base64(format(template, ctx));
        }
    })();

    function ExportSupplierMonthlyData() {
        try {
            tableToExcel();
        } catch (err) {
            bootbox.alert('沒有數據,導出失敗');
        }
    }
    </script>
</html>

 


免責聲明!

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



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