JS导出页面table到Excel表格

<a href="javascript:;" id="export" >导出</a>
<table>
    <thead>
        <tr>
            <th>姓名</th>
            <th>手机</th>
        </tr>
    </thead>
    <tbody id="tableExcel">
        <tr>
            <td>扯淡1</td>
            <td>18888888888</td>
        </tr>
    </tbody>
</table>
<script>
    $("#export").click(function () {
        tableToExcel();
    })

    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><meta charset="UTF-8"><!--[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 () {
            //根据ID获取table表格HTML
            var table = document.getElementById("tableExcel");
            var ctx = { worksheet: 'Worksheet', table: table.innerHTML };
            document.getElementById("export").href = uri + base64(format(template, ctx));
            document.getElementById("export").download = '培训申请管理.xls';
        }
    })()
</script>

转载:https://blog.csdn.net/qq_31634167/article/details/83056744

posted @ 2019-09-05 15:06  时光博客  阅读(2774)  评论(0编辑  收藏  举报