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

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

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

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:

确定