【问题标题】:Save dynamically created table content in excel file using SheetJS使用 SheetJS 将动态创建的表格内容保存在 excel 文件中
【发布时间】:2021-06-13 10:02:21
【问题描述】:

我动态地将行添加到 html 表中,并且我想使用 SheetJs 将表内容保存到 xlsx 文件中。生成的文件是空的。当以这种方式添加表格内容时,在这种情况下是否有可能做到这一点? 我还尝试在创建 xlsx 文件之前添加行。

<!DOCTYPE html>
<html>

<head>
    <script src="https://code.jquery.com/jquery-2.1.4.js"
        integrity="sha256-siFczlgw4jULnUICcdm9gjQPZkw/YPDqhQ9+nAOScE4=" crossorigin="anonymous"></script>
    <script type="text/javascript"
        src="https://cdnjs.cloudflare.com/ajax/libs/amcharts/3.21.15/plugins/export/libs/FileSaver.js/FileSaver.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.15.6/xlsx.full.min.js"></script>

    <style>
        table,
        td {
            border: 1px solid black;
        }
    </style>
</head>

<body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.10.3/xlsx.full.min.js">
    </script>

    <p>Click the button to add a new row at the first position of the
        table and then add cells and content</p>

    <table id="myTable">
        <TR>
        </TR>
    </table>
    <button type="button" id="first" onclick="First('myTable')">Principal</button>
    <button id="button-a">Create Excel</button>
    <script>
        function First(tableID) {
            let table = document.getElementById(tableID)
            table.innerHTML = "<tr>first</tr>";
        }

    </script>

    <script>
        var wb = XLSX.utils.table_to_book(document.getElementById('myTable'), { sheet: "Sheet JS" });
        var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'binary' });
        function s2ab(s) {
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
            return buf;
        }
        $("#button-a").click(function () {
            saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), 'test.xlsx');
        });
    </script>
</body>

</html>

【问题讨论】:

    标签: javascript html jquery ajax sheetjs


    【解决方案1】:

    问题

    1. tr 内的文本,而不是动态内容中的 td。这会产生如下表结构。

    1. XLSX.utils.table_to_book 在创建表格内容之前调用。

    工作演示

    https://jsfiddle.net/aswinkumar863/95zsfg64/1/

    【讨论】:

    • 我唯一的小问题是,当我有一个包含 14 行的表格时,最后一行的第一个单元格会在 2001 年 2 月 28 日打印。你知道为什么吗?
    • 可能与我检索的数据有关,因为此代码适用于表中的更多行..
    • 但我真的不知道为什么表上的值看起来很正常,当传输到 excel 文件时它得到 ##### 值..
    猜你喜欢
    • 2021-06-18
    • 1970-01-01
    • 2023-02-21
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多