[英]Download Google Sheets file and read data using SheetJS on Node
[英]Download excel file created in node using SheetJS/XLXS [NodeJS] [React]
我正在嘗試在節點中使用 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: "array",
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",
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.