Home » excel » c# – OpenXML Spreadsheet get column ordinal index

c# – OpenXML Spreadsheet get column ordinal index

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m creating an Excel export using the OpenXML libraries. I am able to set the cell reference using the default cell references e.g. A1.

As I want to dynamically populate the data across the columns I was wondering if it’s possible to use a numerical co-ordinate reference e.g. Cells[1, 1]?

So instead of doing something like:

Cell cell = InsertCellInWorksheet("A", 1, worksheet);

I would like to do:

Cell cell = InsertCellInWorksheet(columnIndex, rowIndex, worksheet);

I seem to find a lot of examples using the Excel grid reference (“A1”) but nothing for the numerical representation.

Many Thanks

Andy

UPDATE

I have found a way of getting the column headers via the answer for this here which calculates the column name based on a numerical index.

This gets the column fine, I can step through the code and can see it cycling through the columns Z, AA, AB etc. I am now finding that when iterating through the columns if it builds anything past column Z I get the error message Excel found unreadable content in...Do you want to recover the contents of this workbook? If you trust the source of this workbook, click Yes.

This is the code which sets the cells:

int columnIndex = 1;
string col;
uint rowIndex = 60;
foreach (var item in _data)
{
    col = ExcelHelper.GetColumnName(columnIndex);
    ExcelHelper.SetCell(wsp, col, rowIndex, item.PeriodEnd.ToString("dd/MM/yyyy"), excelStylesheet.TableCell);
    columnIndex++;
}

If I hard code col to be “AA” and set rowIndex to be incrementing it works fine but like this it generates an unreadable Excel file.

I can’t see how/why this would be happening as I can see col being set correctly stepping through the code but something appears to be going awry somewhere.

Can anyone help shed any light on what could be causing this or know of an approach to identify the issue better?

Thanks again

Andy

How to&Answers:

you can use the following code

row.Append(newCell);

instead of this

row.InsertBefore(newCell, refCell);

Open XML SDK: get "Unreadable content" error when trying to populate more than 25 columns