Reputation: 13178
I have a sails application that I'm using exceljs
to generate an excel file. Looking at their documenatation:
https://www.npmjs.com/package/exceljs#writing-xlsx
It appears they allow writing to a stream.
// write to a stream
workbook.xlsx.write(stream)
.then(function() {
// done
});
How can I do this when the user is expecting a response?
I read the below:
http://sailsjs.org/documentation/concepts/custom-responses/adding-a-custom-response
http://sailsjs.org/documentation/concepts/custom-responses/default-responses
I also tried res.attachment()
after saving the file and was not successful. Is there something i'm missing?
EDIT
The answer below is almost right. I did the following and it worked. The previous solution had sometimes corrupt files.
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();
});
This worked on my EC2 instance and locally.
Upvotes: 1
Views: 1073
Reputation: 70416
Solution: https://github.com/guyonroche/exceljs/issues/37 write the workbook to the response.
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();
Upvotes: 2