【问题标题】:how to pipe exceljs stream to reply in hapijs如何通过管道传输 exceljs 流以在 hapijs 中回复
【发布时间】:2017-02-28 18:07:56
【问题描述】:

我正在使用 exceljs 生成一个 excel 文件(使用它的流功能)。我不想将文件保存在服务器上然后读取并返回它,而是想直接将 exceljs 流流式传输到 hapijs 中的响应。

function(request, reply) {
  const options = {
    stream: reply, // I need to somehow declare the reply stream here
    useStyles: false,
    useSharedStrings: true
  };

  const workbook = new Excel.stream.xlsx.WorkbookWriter(options);
  workbook.addWorksheet('Test');
  const worksheet = workbook.getWorksheet('Test');

  worksheet.columns = [{
    header: 'product', key: 'product'
  }];

  worksheet.addRow({product: 'MyProduct'}).commit();
  worksheet.commit();
  workbook.commit();

这可能吗?我不能像在 expressjs 中那样直接将回复传递给 Exceljs 流的选项?有什么想法吗?

【问题讨论】:

  • Reply 可以返回一个流,但我会将 exceljs 逻辑包装在您自己的流接口中,您可以将其传递给 hapi 的回复接口,我使用模块 j 来实现这一点.查看this 模块以展示如何包装流,在我的示例中,它是从 excel 转换为 json

标签: stream streaming hapijs exceljs


【解决方案1】:
var wb = new Excel.stream.xlsx.WorkbookWriter();
var sh = wb.addWorksheet('sheet1');
sh.columns = [
    { header: 'Name', key: 'name' },
    { header: 'Age', key: 'age' }
];

sh.addRow(['Ben', 8]);
sh.addRow(['Dave', 10]);

sh.commit();
wb.commit()
.then(function () {
    var stream = wb.stream;
    var b = stream.read();

    reply(b)
    .type('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    .header('Content-Disposition', 'attachment; filename=file.xlsx')
    .header('Content-Length', stream.length);
});

【讨论】:

  • 不鼓励仅使用代码和“试试这个”的答案。请解释为什么以及如何解决 op 的问题。
  • 您可以阅读 exceljs 库站点上的 Streaming XLSX 部分,它在那里解释了使用情况
  • 对不起,如果我之前的评论很粗鲁。尽管您仍可能希望包含额外信息以提高您的答案的长期价值。 “始终引用重要链接中最相关的部分,以防目标站点无法访问或永久离线” - stackoverflow.com/help/how-to-answer
  • github.com/guyonroche/exceljs/blob/master/… - 它在那里解释,虽然没有给出示例
  • 重要的说明是:“如果选项中既没有指定流也没有指定文件名,工作簿编写器将创建一个 StreamBuf 对象,该对象将把 XLSX 工作簿的内容存储在内存中。这个 StreamBuf 对象,它可以通过属性 workbook.stream 访问,可用于通过 stream.read() 直接访问字节或将内容通过管道传输到另一个流。"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
  • 1970-01-01
  • 1970-01-01
  • 2013-12-17
相关资源
最近更新 更多