JS导出页面table到Excel表格

2021-01-21 17:23:26 浏览数 (1)

代码语言:javascript复制
<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>
代码语言:javascript复制
$("#export").click(function () {
   tableToExcel();
})
代码语言: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><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';
        }
    })()

0 人点赞