0

I have to print some data in excel format using excel4node. Within the data I have objects that contains information which I want to transfer to excel format. But for some reason it shows error: TypeError: Cannot read property 'username' of undefined. Inside the object I have property username and its value. Here code below:

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);
Adil
  • 55
  • 2
  • 7

1 Answers1

0

At the bottom of your script, you can see that you are looping over the data.length and attempting to insert it into your cells.

At the top of the page, your data object is not an Array but an object, and indexing an object must be done by the keys and not the index value. This is why it cannot find the username since it's looking for "object.1.username".

Switch your data object to a array if you would like to use index values.

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

now becomes

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