HTML表格数据导出到Excel

时间:2016-08-24 22:30:16

标签: javascript html

我使用以下代码将html数据提取到Excel中。当我点击下载链接时,它会下载一个excel文件,但它是空白的,不包含任何数据。下载文件的大小为1KB。有没有人遇到过 这样的问题?

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
    <meta charset="UTF-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
    <script lang="js">
        function fnExcelReport() {
            var tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
            tab_text = tab_text + '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';

            tab_text = tab_text + '<x:Name>Test Sheet</x:Name>';

            tab_text = tab_text + '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>';
            tab_text = tab_text + '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';

            tab_text = tab_text + "<table border='1px'>";
            tab_text = tab_text + $('#myTable').html();
            tab_text = tab_text + '</table></body></html>';

            var data_type = 'data:application/vnd.ms-excel';

            var ua = window.navigator.userAgent;
            var msie = ua.indexOf("MSIE ");

            if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
                if (window.navigator.msSaveBlob) {
                    var blob = new Blob([tab_text], {
                        type: "application/csv;charset=utf-8;"
                    });
                    navigator.msSaveBlob(blob, 'Test file.xls');
                }
            } else {
                $('#test').attr('href', data_type + ', ' + encodeURIComponent(tab_text));
                $('#test').attr('download', 'Test file.xls');
            }

        }
    </script>
</head>
<body>
    <a href="#" id="test" onClick="javascript:fnExcelReport();">download</a>

    <table id="myTable">
        <thead>
            <tr>
                <td style="padding-right: 30px;"><b>Name</b>

                </td>
                <td style="padding-right: 30px;"><b>Age</b>

                </td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Tester1</td>
                <td>30</td>
            </tr>
            <tr>
                <td>Tester2</td>
                <td>29</td>
            </tr>
            <tr>
                <td>Tester3</td>
                <td>17</td>
            </tr>
        </tbody>
    </table>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

没有下载的Excel不是空白,它的数据位于'tab_text'变量中, 尝试用记事本打开excel文件。你希望在excel中保存什么样的数据?将它保存为'\ n'分隔的行和列'','分隔。