如何使用ExcelJS将流数据写入Excel文件?

huangapple go评论92阅读模式
英文:

How can I write stream data to an Excel file using ExcelJS?

问题

我想使用这段代码将流数据写入Excel文件,但它只创建了一个空文件。我是否漏掉了什么?

  1. const excel = require("exceljs");
  2. async function processUpload(stream, filename) {
  3. let counter = 0;
  4. const options = {
  5. filename,
  6. useStyles: true,
  7. useSharedStrings: true,
  8. };
  9. const workbook = new excel.stream.xlsx.WorkbookWriter(options);
  10. const worksheet = workbook.addWorksheet("Sheet1");
  11. stream.on("data", (row) => {
  12. counter++;
  13. worksheet.addRow(row);
  14. });
  15. stream.on("end", () => {
  16. workbook.commit().then(() => {
  17. console.log("Workbook committed and uploaded to GCS.", counter);
  18. return filename;
  19. });
  20. });
  21. stream.on("error", (err) => console.error(err));
  22. }

如有需要,可以提供更多帮助。

英文:

I want to write stream data the Excel file using this code but it just creates an empty file. Am I missing anything here?

  1. const excel = require("exceljs");
  2. async function processUpload(stream, filename) {
  3. let counter = 0;
  4. const options = {
  5. filename,
  6. useStyles: true,
  7. useSharedStrings: true,
  8. };
  9. const workbook = new excel.stream.xlsx.WorkbookWriter(options);
  10. const worksheet = workbook.addWorksheet("Sheet1");
  11. stream.on("data", (row) => {
  12. counter++;
  13. worksheet.addRow(row);
  14. });
  15. stream.on("end", () => {
  16. workbook.commit().then(() => {
  17. console.log("Workbook committed and uploaded to GCS.", counter);
  18. return filename;
  19. });
  20. });
  21. stream.on("error", (err) => console.error(err));
  22. }

答案1

得分: 1

所以我运行了你的代码,并发现你需要指定列。假设你接收的数据是带有以下键的 JSON 对象:

  1. {
  2. name: 'John',
  3. age: 23,
  4. department: 'sales'
  5. }

然后你可以这样做:

  1. worksheet.columns = [
  2. { key: 'name', header: 'Name', width: 6 },
  3. { key: 'age', header: 'Age', width: 6 },
  4. { key: 'department', header: 'Department', width: 6 }
  5. ]

其中 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

  1. {
  2. name: 'John',
  3. age: 23,
  4. department: 'sales'
  5. }

Then you can do the following

  1. worksheet.columns = [
  2. { key: 'name', header: 'Name', width: 6 },
  3. { key: 'age', header: 'Age', width: 6 },
  4. { key: 'department', header: 'Department', width: 6 }
  5. ]

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

huangapple
  • 本文由 发表于 2023年6月26日 20:10:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76556554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定