Search code examples
c#.netaspose

Obtaining cell name in Aspose Cells


I am looking to obtain the name of a cell given a row/column pair. I need a name to use in a formula. For example, I would like to set cell (3, 4) to a formula that adds the values of cells (4, 4) and (5, 4).

Cell (3, 4) is D5; (4, 4) is E5, and (5, 4) is F5. Therefore, my formula should look like this:

=E5+F5

I can format my formula like this:

const int col = 3;
const int row = 4;
worksheet.Cells[row, col].Formula = string.Format(
    "={0}{1}+{2}{3}"
,   (char)('A'+col+1) // <<== Broken, do not use
,   row+1
,   (char)('A'+col+2) // <<== Broken, do not use
,   row+1
);

This works fine for columns A..Z, but breaks for columns with names further to the right. I could use a trick described in this Q&A, but the problem looks so basic that it shouldn't require coding on my part.


Solution

  • You do not need to do this the hard way, because Aspose did it for you. Their CellsHelper class has CellIndexToName method, which does exactly what you need:

    const int col = 3;
    const int row = 4;
    worksheet.Cells[row, col].Formula =
        $"={CellsHelper.CellIndexToName(row, col+1)}+{CellsHelper.CellIndexToName(row, col+2)}";