我有一个 sails 应用程序,我正在使用 exceljs
生成 Excel 文件。查看他们的文档:
https://www.npmjs.com/package/exceljs#writing-xlsx
看起来它们允许写入流。
// write to a stream
workbook.xlsx.write(stream)
.then(function() {
// done
});
当用户期待响应时,我该如何执行此操作?
我阅读了以下内容:
http://sailsjs.org/documentation/concepts/custom-responses/adding-a-custom-response
http://sailsjs.org/documentation/concepts/custom-responses/default-responses
我在保存文件后也尝试了 res.attachment()
但没有成功。我有什么遗漏的吗?
编辑
下面的答案几乎是正确的。我做了以下操作并且成功了。以前的解决方案有时会损坏文件。
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
return workbook.xlsx.write(res)
.then(function() {
res.end();
});
这在我的 EC2 实例和本地都有效。
最佳答案
解决方案:https://github.com/guyonroche/exceljs/issues/37将工作簿写入响应。
var Excel = require('exceljs');
var workbook = new Excel.Workbook();
var sheet = workbook.addWorksheet("My Sheet");
res.setHeader('Content-Type', 'application/vnd.openxmlformats');
res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
workbook.xlsx.write(res);
res.end();
关于node.js - Saisjs下载数据流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39336507/