Home > other >  nodejs exceljs addrow specify
nodejs exceljs addrow specify

Time:12-24

i have response json like these

{
    "success": true,
    "message": "load yogithesymbian data",
    "total_items": 74,
"results": [
        {
            "id": 1,
            "created_at": "2021-12-23T02:41:00.000Z",
            "child": {
                "id": 1,
                "number": 2, // i would use this column on my Sheet
             }
        }
     ]
}

then my column code:

  let workbook = new excel.Workbook();

  let worksheetDT = workbook.addWorksheet("tes");
  worksheetDT.columns = [
    { header : "ID", key: "id", width : 25 }, // this works
    { header : "Number  ", key: "child.number", width : 25 },// how to set the number ?
  ];

i have added the json like these ( i am using Model.findAll()


worksheetDT.addRows(...results);

my query :

var results = [];
  await Model.findAll({
      include: [
        {
            model: child,
        },
      ],
    }).then( async (result) => {
      results.push(result);
  });

the field of number always blank how to know what key for the field of number ?

CodePudding user response:

i couldnt test it, but im wondering, this line works:

{ header : "ID", key: "id", width : 25 }

because of results is an array.

Does it work with:

results[0].child.number

CodePudding user response:

Yogi, are you sure that exceljs allows dot notation while adding rows?

In anycase, you can do this:

  let workbook = new excel.Workbook();

  let worksheetDT = workbook.addWorksheet("tes");
  worksheetDT.columns = [
    { header : "ID", key: "id", width : 25 }, // this works
    { header : "Number  ", key: "number", width : 25 }
  ];

function convertToRow(result) {
  
  const row = { id: result.id, number: result.child.number};

  return row;
}
...
var results = [];
await Model.findAll({
 include: [{
   model: child,
  }],
}).then( async (result) => {
 const row = convertToRow(result);
 results.push(row);
});

Note that I have changed the column key for number and building a object that has the signature expected by columns in convertToRow function.

  • Related