英文:
How can I write stream data to an Excel file using ExcelJS?
问题
我想使用这段代码将流数据写入Excel文件,但它只创建了一个空文件。我是否漏掉了什么?
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));
}
如有需要,可以提供更多帮助。
英文:
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));
}
答案1
得分: 1
所以我运行了你的代码,并发现你需要指定列。假设你接收的数据是带有以下键的 JSON 对象:
{
name: 'John',
age: 23,
department: 'sales'
}
然后你可以这样做:
worksheet.columns = [
{ key: 'name', header: 'Name', width: 6 },
{ key: 'age', header: 'Age', width: 6 },
{ key: 'department', header: 'Department', width: 6 }
]
其中 key 应该是 JSON 字段名,header 将是 Excel 表格中的列标题,你可以选择它成为任何你想要的内容。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论