0

How to push values from array into row in exceljs?

i try with this:

const columns = ['string', 'string2', 'string3'];

for(let i=0; i < columns.length; i++) {
    workSheet.getRow(1).values  = [dto.columns[i]];
}

but this code add only one item from the columns list :/

have anybody any idea how to resolve this problem? I must add objects from array, I know that, i can do this:

workSheet.getRow(1).values  = ['string','string2', 'string3'];

but this is not for me :( thanks for any help

  • `workSheet.getRow(1).values.push([dto.columns[i]]);`? – dave Jul 28 '20 at 17:36
  • Can you explain better why `workSheet.getRow(1).values = columns` is *not for me*? – Anurag Srivastava Jul 28 '20 at 17:36
  • @dave i can't return me `This expression is not callable. Not all constituents of type 'string | number | boolean | Date | CellErrorValue | CellRichTextValue | CellHyperlinkValue | CellFormulaValue | CellSharedFormulaValue | ((...items: CellValue[]) => number)' are callable. Type 'string' has no call signatures.` –  Jul 28 '20 at 17:39
  • @AnuragSrivastava because I can't hardcoded names of column, i must add from the array because my users can choose columns to excel file –  Jul 28 '20 at 17:40

1 Answers1

0

You are reassigning the value inside the for loop. So, you will always get the last item inside the values property. You can initialize the values as empty array before for loop and then try putting the item in the values.

const columns = ['string', 'string2', 'string3'];
workSheet.getRow(1).values = [];
for(let i=0; i < columns.length; i++) {
    workSheet.getRow(1).values.push(dto.columns[i]);
}
gaurav soni
  • 206
  • 1
  • 10
  • i'm using typescript and at `push` thorw me error: `This expression is not callable. Not all constituents of type 'string | number | boolean | Date | CellErrorValue | CellRichTextValue | CellHyperlinkValue | CellFormulaValue | CellSharedFormulaValue | ((...items: CellValue[]) => number)' are callable. Type 'string' has no call signatures.` –  Jul 28 '20 at 18:32
  • You might need to do the typecasting to make it compatible. Can you let me know what is the type of values? – gaurav soni Jul 28 '20 at 19:09
  • my `columns` is in fact `columns: string[];` in my dto –  Jul 28 '20 at 19:34
  • Can you try (workSheet.getRow(1).values as string[]).push(dto.columns[i]); – gaurav soni Jul 28 '20 at 19:52