Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get cell by name with exceljs?

Tags:

exceljs

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 }
];
like image 672
Tran B. V. Son Avatar asked Jan 26 '23 04:01

Tran B. V. Son


1 Answers

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.

like image 56
dawaltco Avatar answered May 19 '23 00:05

dawaltco