下载使用SheetJS/XLXS [NodeJS] [React]在节点中创建的excel文件

toe95027  于 2023-02-21  发布在  Node.js
关注(0)|答案(1)|浏览(124)

我尝试使用节点中的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显示““文件格式或文件扩展名无效...”

aiazj4mn

aiazj4mn1#

我通过在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",
        });

相关问题