【问题标题】:Cannot read property 'username' of undefined, excel4node cannot read property username无法读取未定义的属性“用户名”,excel4node 无法读取属性用户名
【发布时间】:2021-11-04 23:20:02
【问题描述】:

我必须使用 excel4node 以 excel 格式打印一些数据。在数据中,我有一些对象,其中包含我想转换为 excel 格式的信息。但由于某种原因,它显示错误:TypeError:无法读取未定义的属性“用户名”。在对象内部,我有属性用户名及其值。 下面是代码:

const wb = new xl.Workbook();
const data = {};
data = {
    username: 'name',
    department: 'department',
    title: 'title',
    percentage: 23,
    correct: 27,
    date: 2021-09-03T16:38:05.107Z
}

const fileName = "Excel.xlsx";
const filePath = path.resolve(__dirname, "../.././public/files/", fileName);

const ws = wb.addWorksheet("Sheet 1");

const style = wb.createStyle({
font: {
  color: "FFFFFFFF",
  size: 12,
},
});

const form = [
"name",
"name",
"name",
"name",
"name",
"name",
];

for (let i = 0; i < form.length; i++) {
ws.cell(1, i + 1)
  .string(form[i])
  .style(style);
switch(i) {
  case 1:
    ws.column(2).setWidth(30);
    break;
  case 3:
    ws.column(4).setWidth(30);
    break;
  case 4:
    ws.column(5).setWidth(30);
    break;
  case 5:
    ws.column(6).setWidth(30);
    break;
}
}

for(let i = 1; i <= data.length; i++) {
ws.cell(i + 1, 1).number(i);
ws.cell(i + 1, 2).string(data[i].username);
ws.cell(i + 1, 3).date(data[i].date.toString());
ws.cell(i + 1, 4).string(data[i].department);
ws.cell(i + 1, 5).number(data[i].percentage);
ws.cell(i + 1, 6).number(data[i].correct);
}
wb.write(filePath);

【问题讨论】:

    标签: node.js excel4node


    【解决方案1】:

    在脚本的底部,您可以看到您正在循环遍历 data.length 并尝试将其插入到您的单元格中。

    在页面顶部,您的数据对象不是数组而是对象,并且索引对象必须通过键而不是索引值来完成。这就是为什么它找不到用户名,因为它正在寻找“object.1.username”。

    如果您想使用索引值,请将您的数据对象转换为数组。

    const data = {};
    data = {
        username: 'name',
        department: 'department',
        title: 'title',
        percentage: 23,
        correct: 27,
        date: 2021-09-03T16:38:05.107Z
    }
    

    现在变成了

    const data = [{
        username: 'name',
        department: 'department',
        title: 'title',
        percentage: 23,
        correct: 27,
        date: 2021-09-03T16:38:05.107Z
    }];
    

    【讨论】:

      猜你喜欢
      • 2019-07-27
      • 2016-05-08
      • 2021-06-15
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 2021-08-03
      • 2017-03-09
      相关资源
      最近更新 更多