I want to write stream data the Excel file using this code but it just creates an empty file. Am I missing anything here?
const excel = require("exceljs");
async function processUpload(stream, filename) {
let counter = 0;
const options = {
filename,
useStyles: true,
useSharedStrings: true,
};
const workbook = new excel.stream.xlsx.WorkbookWriter(options);
const worksheet = workbook.addWorksheet("Sheet1");
stream.on("data", (row) => {
counter++;
worksheet.addRow(row);
});
stream.on("end", () => {
workbook.commit().then(() => {
console.log("Workbook committed and uploaded to GCS.", counter);
return filename;
});
});
stream.on("error", (err) => console.error(err));
}
So I ran your code and figured that you need to specify the columns. Let say the data your are receiving is json objects with following keys
{
name: 'John',
age: 23,
department: 'sales'
}
Then you can do the following
worksheet.columns = [
{ key: 'name', header: 'Name', width: 6 },
{ key: 'age', header: 'Age', width: 6 },
{ key: 'department', header: 'Department', width: 6 }
]
Where key should be the json field name. And header will be the column header in excel sheet and you can choose it to be whatever you want