javascript - 下载使用 SheetJS/XLXS 在 Node 中创建的 excel 文件 [NodeJS] [React]

标签 javascript node.js excel xlsx sheetjs

我正在尝试在 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/

相关文章:

javascript - 使用 Netlify URL 问题部署的 React Redux 应用程序

工作表中的 VBA ActiveX 标签

vba - Excel VBA : SaveCopyAs with different file extenstion

node.js - 如何在 sailsjs 中验证模型

javascript - 使用 html-pdf 包动态生成 pdf

javascript - 如何获取正在运行的函数所属的对象名?

excel - vba-sum 和 group by 不使用 sql-adodb

javascript - 如何创建一个巨大的复选框表(我的意思是巨大!)

javascript - 如何获取jquery post函数的返回值?

javascript - 在 Django 项目中使用 JavaScript 的最合适的方式是什么?