I have this function that will run through express.js
controller.js
const {convertJsontoExcel} = require('./convertJsontoExcel');
const Controller = {
downloadexcel: async (req, res, next) => {
try {
const obj = [
{
id: 222,
name: class
},
{
id: 113,
name: class2
}
]
await convertJsontoExcel(req, res, obj)
} catch (error) {
const formattedError = {
kode: 500,
msg: error.message,
detail: error.stack
}
res.status(500).json(formattedError);
}
},
}
}
module.exports = Controller;
router.js
const express = require('express');
const router = express.Router();
const controller= require('./controller');
router.use(express.static(__dirname + '/public'));
router.post('/downloadexcel', controller.downloadexcel)
module.exports = router
convertJsontoExcel.js
const convertJsontoExcel = async (req, res, jsonData) => {
const workBook = new excel.stream.xlsx.WorkbookWriter({
stream: res
});
const workSheet = workBook.addWorksheet('Laporan');
// Set the column
console.log("Set the column")
workSheet.columns = [
{ header: ' Id', key: 'id', width: 25 },
{ header: ' name', key: 'name', width: 25 },
];
console.log("Looping for adding the data to excel")
for (let i = 0; i < jsonData.length; i++) {
const r = i + 1;
workSheet.addRow(jsonData[i]).commit();
}
// console.log("commit")
// await workBook.commit();
// await workBook.xlsx.write();
res.setHeader("Content-Type", "application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet");
res.setHeader("Content-Disposition", "attachment; filename=Rep1ort.xlsx");
workBook.xlsx.write(res).then(function () {
res.status(200).end();
});
}
module.exports = {
convertJsontoExcel
}
I want to set a download file from generated excel file using exceljs but when i run this code, its always return Error: Can't render headers after they are sent to the client. WHat's wrong with my code ?
Surprisingly, i still can download the file, but the machine will eventually shutdown because unhandled error.
How to set download file for so it can downloaded from browser file ?