I want to launch a browser download of an excel file generated in my backend, but I can't figure how to pass that kind of response.
app.get('/all', function (req, res) {
db.query(...) LIMIT 20000;")
.then(function (data) {
let result = []
data.forEach(element => {
result.push(element)
})
/* make the worksheet */
var ws = XLSX.utils.json_to_sheet(data);
/* add to workbook */
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "All");
XLSX.writeFile(wb, 'alltest1.xlsx'); //This saves the file in my server but I don't know how to send it as a response.
console.log('Ready');
res.send(result);
})
.catch(function (error) {
console.log("ERROR:", error)
})
})
I have been trying to create the excel in the frontend but chrome runs out of memory due to the big amount of data I think. I have also try to pass a buffer but the file I was getting seems to be corrupted.
Set the response header Content-Disposition and Content-Type of the file which tells the browser that file is send as response
res.setHeader('Content-Disposition',
"attachment; filename='alltest1'; filename*=UTF-8\'\'alltest1.xlsx");
res.setHeader('Content-Type', "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
and send the file content as response
res.send(wb)
OR you can also use res.download.
res.download(filePath, fileName, (err) => { if (err) console.log(err); })