【问题标题】:Exporting html table to excel file (.xlsx), getting corrupted file on download将 html 表导出到 excel 文件 (.xlsx),下载时文件损坏
【发布时间】:2022-01-24 22:21:32
【问题描述】:

我正在尝试将 html 文件导出到 .xlsx 文件,但下载后运气不好,它说已损坏。 如果并且能够为 .xls 扩展名打开,它工作正常,但我需要 .xlsx 扩展名。

下面是我的代码:

function convertBase64ToByteArray(base64String: any) {
    const raw = window.atob(base64String);
    const rawLength = raw.length;
    const array = new Uint8Array(new ArrayBuffer(rawLength));

    for (let i = 0; i < rawLength; i++) {
        array[i] = raw.charCodeAt(i);
    }

    return new Uint8Array(array);
}

function createBlob(data: any, contentType: any) {
    if (typeof Blob !== "undefined") {
        return new Blob([data], {
            type: contentType
        });
    }

    throw new Error("Download is not supported");
}

function downloadInternal(blobUrl: any, filename: string) {
    const a = document.createElement("a");
    if (a.click) {
        a.href = blobUrl;
        a.target = "_parent";
        
        if ("download" in a) {
            a.download = filename;
        }
       
        (document.body || document.documentElement).appendChild(a);
        a.click();
        a.parentNode.removeChild(a);
    } else {
        if (window.top === window && blobUrl.split("#")[0] === window.location.href.split("#")[0]) {
            const padCharacter = blobUrl.indexOf("?") === -1 ? "?" : "&";
            blobUrl = blobUrl.replace(/#|$/, padCharacter + "$&");
        }
        window.open(blobUrl, "_parent");
    }
}

function download(blob: any, filename: string) {
    if ((navigator as any).msSaveBlob) {
        
        (navigator as any).msSaveBlob(blob, filename);
        return;
    }

    const blobUrl = URL.createObjectURL(blob);
    this.downloadInternal(blobUrl, filename);
}

function exportToExcel(headerHtml: any, tableHtml: any, workSheetName: any, downloadFileName: any) {
    const 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><!--[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><tr><td colspan="30">{header}</td></tr><tr><td colspan="30"></td></tr></table>{table}</body></html>';
    const base64 = function (s: any) {
        return window.btoa(s);
    };
    const format = function (s: any, c: any) {
        return s.replace(/{(\w+)}/g, function (_m: any, p: any) {
            return c[p];
        });
    };

    const ctx = { worksheet: workSheetName || "Worksheet", header: headerHtml, table: tableHtml };
    const data = this.convertBase64ToByteArray(base64(format(template, ctx)));
    const blob = this.createBlob(data, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    this.download(blob, downloadFileName || "download.xlsx");
}

从 js 文件中我调用如下:

 const printingHtml = generateHtmlForExport();
                        exportUtil.exportToExcel(headerHtml:
                            " ",
                            tableHtml:printingHtml,
                            WorksheetfileName:"fileName"),
                           downloadfilename:"fileName" + ".xlsx"
                        );

如果我打开下载的文件,它会显示消息:

Excel 无法打开文件(文件名).xlsx,因为文件格式或文件扩展名无效。验证文件没有损坏,并且文件扩展名与文件格式匹配。

【问题讨论】:

    标签: javascript c# jquery typescript


    【解决方案1】:

    通过 Base64 或 blob 将 HTML 字符串导出到 XLS 并不会真正导出 XLS 文件,因为 Excel 可以打开伪装成 XLS 的 HTML 文件。但是XLSX格式是一个包含多个XML文件的ZIP文件,所以打开Html文件会报错。

    如果您可以使用第三方 JavaScript,这很容易解决,例如:https://github.com/SheetJS/sheetjs

    相关问题:Exporting HTML table to xlsx

    【讨论】:

    • 所以我们无法使用 blob 导出为 .xlsx 格式?
    • Blob可用,错误是你创建的HTML文件,需要找第三方javascript生成正确的文件。
    猜你喜欢
    • 2016-01-19
    • 1970-01-01
    • 2017-07-14
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 2017-09-13
    相关资源
    最近更新 更多