如何管道exceljs流回复hapijs

时间:2017-02-28 18:07:57

标签: stream streaming hapijs exceljs

我正在使用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流的选项吗?有什么想法吗?

1 个答案:

答案 0 :(得分: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);
});