我正在尝试在 Node 中使用 SheetJS 生成 xlsx
文件。然后在我的前端有一个按钮可以调用此路由并下载文件。目前我有以下内容:
// backend code
export function exportExcel(req: Request, res: Response) {
try {
const workbook = utils.book_new();
const fileName = "sample";
const dataSheet = utils.json_to_sheet(sampleData);
utils.book_append_sheet(workbook, dataSheet, fileName.replace("/", ""));
const binaryWorkbook = write(workbook, {
type: "array",
bookType: "xlsx",
});
return res.status(OK).send(binaryWorkbook);
} catch (_error) {
return res.sendStatus(500)
}
}
然后在前端我有以下内容:
const handleExcelExport = () => {
const { data } = await axios.get(
`/export-excel`,
{
responseType: "blob",
}
).then(response => {
const blob = new Blob([response], {
type: "application/octet-stream",
});
const link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
}
}
// I simply call the above in the onClick handler in a button
<button onClick={handleExcelExport}> Export excel </button>
当我点击按钮时,我可以看到出现一个下载文件,但我无法打开它。 MS Excel 提示“文件格式或文件扩展名无效...”
最佳答案
我通过在 BE 中更改为以下内容来修复:
const binaryWorkbook = write(workbook, {
type: "buffer",
bookType: "xlsx",
});
并且还根据文档添加标题:
res.setHeader(
"Content-Disposition",
'attachment; filename="SheetJSNode.xlsx"'
);
res.setHeader("Content-Type", "application/vnd.ms-excel");
然后在前端我将响应类型和内容类型更改为
{
responseType: "arraybuffer",
}
Blob 内容类型
const blob = new Blob([response], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
关于javascript - 下载使用 SheetJS/XLXS 在 Node 中创建的 excel 文件 [NodeJS] [React],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73550410/