【发布时间】: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