【问题标题】:Download excel file created in node using SheetJS/XLXS [NodeJS] [React]下载使用 SheetJS/XLXS [NodeJS] [React] 在节点中创建的 excel 文件
【发布时间】:2023-02-21 14:43:32
【问题描述】:

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

【问题讨论】:

    标签: javascript node.js excel xlsx sheetjs


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-01
      • 2016-11-06
      • 1970-01-01
      • 2022-01-07
      • 2020-06-28
      • 1970-01-01
      相关资源
      最近更新 更多