javascript - 如何使用 Exceljs 通过 Express 生成 xlsx 文件并将其发送给客户端?

标签 javascript node.js express response exceljs

我想在我的 Express 应用程序中分离 Controller 和服务,目前,我有一个使用 ExcelJS 生成 XLSX 文件的服务,我想重用该服务,所以我不想将响应对象传递给该服务,有没有办法可以将文件从服务返回到 Controller ?

现在我有以下内容

const generateXLSX = (res, data) => {
  let baseFile = "path/to/template.xlsx";
  let wb = new Excel.Workbook();
  wb.xlsx
    .readFile(baseFile)
    .then(async () => {
       // add data to template
     }
      await wb.xlsx.write(res);
      res.end();
    })
    .catch((err) => {
      console.log(err);
      res.status(500);
    });
};

在这个函数中我使用了服务中的响应对象,我想知道是否有一种方法可以在不使用write(res)的情况下返回文件,并在 Controller 中发送它

最佳答案

您的generateXLSX 函数可能会返回 "pass-through" readable stream然后将其通过管道传输到 res 对象中。有点像

const {PassThrough} = require("stream");
function generateXLSX(data) {
  let baseFile = "path/to/template.xlsx";
  let wb = new Excel.Workbook();
  let readable = new PassThrough();
  wb.xlsx
    .readFile(baseFile)
    .then(async function() {
      // add data to template
      await wb.xlsx.write(readable);
      readable.end();
    })
    .catch((err) => {
      readable.destroy(err);
    });
  return readable;
}

app.use("/path", function(req, res) {
  generateXLSX(req.query.data).pipe(res);
});

关于javascript - 如何使用 Exceljs 通过 Express 生成 xlsx 文件并将其发送给客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71146252/

相关文章:

javascript - Angular2,尝试添加新模块时出错

javascript - 使div高度响应内容

node.js - 仅使用 shell 部署应用程序

javascript - 连接已签名的 cookie 解析错误

express - Route.patch 中的 For 循环不起作用。 || Express.js

javascript - 我可以在没有 Ender 的情况下将 qwery 与 bean 一起使用吗?

javascript - 如何从 html 中删除不需要的文本

javascript - 在 Node JS 中等待一个函数完成,然后再触发下一个函数

javascript - 在 Javascript 中导入

node.js - 如何通过 sudo 在生产模式下运行 node.js Express?