How To Read Data From Column A From Excel

Viewed 922

I'm trying to get the data from a given column from excel in nodejs (for example, column "Emails"), work with the data and then export the result in the same excel, in a new column named "Emails-Result".

This is what I tried by fetching the data:

const xlsx = require('xlsx');


const emails = [];
                        var workbook = xlsx.readFile(`./view/assets/uploads/${filename}`);
                        var first_sheet_name = workbook.SheetNames[0];
                        var address_of_cell = 'Emails';
                        var worksheet = workbook.Sheets[first_sheet_name];
                        var desired_cell = worksheet[address_of_cell];
                        emails.push(desired_cell.v);

                        console.log(emails);

but I get this error:

TypeError: Cannot read property 'v' of undefined

so the data couldn't be retrieved.

Also, how can I make a new column (if not exists) and add the result in it?

Any ideas, please?

1 Answers

You cannot just pass the string and expect that you'll get that column, you have to find the name of the cells which you will accrue.

const columnName = Object.keys(worksheet).find(key=> worksheet[key].v === address_of_cell);

Finding the name is done by passing the 'Emails' and searching which cell names are to be parsed.

This will work:

const xlsx = require('xlsx');


const emails = [];
var workbook = xlsx.readFile(`./view/assets/uploads/${filename}`);
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = 'Emails';
var worksheet = workbook.Sheets[first_sheet_name];
const columnName = Object.keys(worksheet).find(key=> worksheet[key].v === address_of_cell);

for (let key in worksheet) {
  if (key.toString()[0] === columnName[0]) {
    emails.push(worksheet[key].v);
  }
}
console.log('Result list', emails)

Likewise, instead of the for in loop you could stay functional and avoid array declaration and worksheet object reference

const emails = Object.entries(worksheet)
  .filter(([key, value]) => key.toString()[0] === columnName[0])
  .map(([key, value]) => value.v)
Related