6

For now, I have to hardcode like this

var cell = worksheet.getCell('A1');

But I want to define my cell by name like data and access the cell by:

var cell = worksheet.getCell('data');

a busy cat

How can I do that with exceljs ? Thank you very much!

Note: The only solution seems to solve my problem is to add column/row headers and define key, but I don't want to do that in my code:

worksheet.columns = [
  { header: 'Id', key: 'id', width: 10 }
];
Tran B. V. Son
  • 759
  • 2
  • 12
  • 31

2 Answers2

6

Just like to suggest another way. I used console.table() to check what column-name and key in a worksheet. I didn't have any key assign to column-name. So we iterate first row and assign cell.text to key.

console.table(worksheet.columns);

worksheet.getRow(1).eachCell((cell, colNumber) => {
  worksheet.getColumn(colNumber).key = cell.text;
});

console.table(worksheet.columns);


worksheet.getRow(2).getCell("UserName").value;
Pankaj Salunkhe
  • 235
  • 1
  • 5
  • 8
5

There doesn't seem to be a built-in method, as far as I can tell. Here's a function that should do the trick:

function getCellByName(worksheet, name) {
    var match;
    worksheet.eachRow(function (row) {
        row.eachCell(function (cell) {
            for (var i = 0; i < cell.names.length; i++) {
                if (cell.names[i] === name) {
                    match = cell;
                    break;
                }
            }
        });
    });
    return match;
}

With ES6:

const getCellByName = (worksheet, name) => {
    let match
    worksheet.eachRow(row => row.eachCell(cell => {
        if (cell.names.find(n => n === name)) {
            match = cell
        }
    }))
    return match
}

That may end up being infeasible with very large worksheets, as you have to iterate through every non-null cell in the sheet.

If you're looking for something with that functionality built-in, I haven't tried it yet but xlsx-populate looks promising.

Jérôme Richard
  • 41,678
  • 6
  • 29
  • 59
dawaltco
  • 338
  • 1
  • 11