为什么 JavaScript 代码导出到 Excel 可以使用旧的 Office 扩展 xls,但不能使用 xlsx?

问题描述 投票:0回答:1

我正在使用 JAVASCRIPT 将 html 表导出到 excel。我面临的问题是无法导出到 Excel Office 新版本,扩展名

xlsx
.

但它工作正常并导出到旧版本的 Office excel,扩展名

xls
.

当从 html 表导出到带有

xlsx
扩展名的 excel 新版本时,它给我错误

cannot open file `.xlsx` because file extension is not valid or file corrupted .

所以如何解决此问题以使用

xlsx
扩展并打开新版本 excel 。

`function getselected_civilid() {
    debugger
    var selectedCivilIds = [];
    $("input[name='statusCheckbox']:checked").each(function () {
        selectedCivilIds.push($(this).val());
    });

    if (selectedCivilIds.length > 0) {
        // Create an HTML table with headers
        var table = "<table><tr><th>م</th><th>رقم السجل التجاري</th><th>رقم الترخيص</th><th>رقم الجهه المدني</th><th>الكيان القانوني</th><th>المحافظة</th><th>القطاع</th><th>كود النشاط الدولى</th><th>اسم المنشأة</th><th>العنوان</th><th>الرقم الالي للعنوان</th><th>المدينة</th><th>رقم التليفون</th><th>البريد الالكترونى</th></tr>";

     
        $("input[name='statusCheckbox']:checked").each(function () {
            var row = $(this).closest("tr"); // Get the parent row of the checkbox
            var cells = row.find("td"); // Get all the cells in the row

            table += "<tr>";
            cells.each(function () {
                table += "<td>" + $(this).text() + "</td>"; // Add each cell value to the table
            });
            table += "</tr>";
        });

        table += "</table>";

     
        var blob = new Blob([table], {
            type: "application/vnd.ms-excel;charset=utf-8"
        });
 
        var link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = "LastData.xls"; // Set the filename for the downloaded file
        link.click();
    }
}`

调试时

var table
它给我html表格脚本作为下面的小提琴所以如何导出到excel
xlsx 
新版本

https://jsfiddle.net/36s1qhov/

javascript html jquery css export-to-excel
1个回答
0
投票

“xlsx”不仅仅是一个文件扩展名,它实际上是一种包含 XML 和其他文件的 zip 包格式。 你不能只将文件命名为“something.xlsx”,你需要将它打包。
为此,请使用现有库,例如 https://www.npmjs.com/package/xlsx

© www.soinside.com 2019 - 2024. All rights reserved.