Home > Net >  Getting same object when parsing worksheet to array
Getting same object when parsing worksheet to array

Time:12-15

I'm trying to make my own worksheet to object-array in node with exceljs. Basically I want to turn the rows to objects with the first row's values being the key and the actual row's values being the value. I get back an object with the right keys but always the same values (namely the last row's values).

What am I doing wrong? Is it the async? Also ignore the empty item, I know it's bad index.

Code:

import Excel from 'exceljs'

const parseWorkbookToObj = async (filename, worksheetNumber) => {

    var row = {}
    var rows = []

    const workbook = new Excel.Workbook();
    await workbook.xlsx.readFile(filename);
    
    const worksheet = workbook.getWorksheet(worksheetNumber);

    for (var i = 1; i <= worksheet.rowCount; i  ){
        for(var j = 2; j <= worksheet.columnCount; j  ){
            var header = await worksheet.getRow(1).values[j]
            var value = await worksheet.getRow(i).values[j];
            row[header] = value;
        }

        rows[i] = row;
    }

    return rows;
    
}

export default parseWorkbookToObj

Example worksheet: image

Output:

[
  <1 empty item>,
  {
    'Header 2': 'Value 9',
    'Header 3': 'Value 10',
    'Header 4': 'Value 11'
  },
  {
    'Header 2': 'Value 9',
    'Header 3': 'Value 10',
    'Header 4': 'Value 11'
  },
  {
    'Header 2': 'Value 9',
    'Header 3': 'Value 10',
    'Header 4': 'Value 11'
  },
  {
    'Header 2': 'Value 9',
    'Header 3': 'Value 10',
    'Header 4': 'Value 11'
  }
]

CodePudding user response:

declare row variable inside the loop.

    for (var i = 1; i <= worksheet.rowCount; i  ){
        let row = {}
        for(var j = 1; j <= worksheet.columnCount; j  ){
             var header = await worksheet.getRow(1).values[j]
            var value = await worksheet.getRow(i).values[j];
            row[header] = value;
        }

        rows[i] = row;
    }

  • Related