美文网首页
table导出为excel

table导出为excel

作者: 芸芸众生ing | 来源:发表于2020-12-29 15:19 被阅读0次
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <table id="table">
        <tr>
            <th>asf</th>
            <th>asf</th>
            <th>asf</th>
        </tr>
        <tr>
            <td>asf</td>
            <td>asf</td>
            <td>asf</td>
        </tr>
    </table>
    <script>
        function base64(content) {
            return window.btoa(unescape(encodeURIComponent(content)));
        }
        function tableToExcel(tableID, fileName) {
            var excelContent = document.querySelector(tableID).innerHTML;
            var excelFile = "<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'>";
            excelFile += "<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>";
            excelFile += "<body><table width='10%'  border='1'>";
            excelFile += excelContent;
            excelFile += "</table></body>";
            excelFile += "</html>";
            var link = "data:application/vnd.ms-excel;base64," + base64(excelFile);
            var a = document.createElement("a");
            a.download = fileName + ".xlsx";
            a.href = link;
            a.click();
        }
        tableToExcel('#table', 'table')
    </script>
</body>

</html>

相关文章

网友评论

      本文标题:table导出为excel

      本文链接:https://www.haomeiwen.com/subject/krnfoktx.html