In ClosedXML, is there anyway to get the column letter from column header name?

leora picture leora · Apr 11, 2015 · Viewed 13.5k times · Source

I have an excel worksheet that has column headers and I don't want to hard code the column letter or index so I am trying to figure out how I could make it dynamic. I am looking for something like this:

var ws = wb.Worksheet("SheetName");

var range = ws.RangeUsed();
var table = range.AsTable();

string colLetter = table.GetColumnLetter("ColHeader");

foreach (var row in table.Rows())
{
  if (i > 1)
  {
    string val = row.Cell(colLetter).Value.ToString();
  }
  i++;
}

Does ClosedXML support anything like the made up GetColumnLetter() function above so I don't have to hard code column letters?

Answer

christophano picture christophano · Apr 11, 2015

Sure, get the cell you want using a predicate on the CellsUsed collection on the row with the headers, then return the column letter from the column.

public string GetColumnName(IXLTable table, string columnHeader)
{
    var cell = table.HeadersRow().CellsUsed(c => c.Value.ToString() == columnHeader).FirstOrDefault();
    if (cell != null)
    {
        return cell.WorksheetColumn().ColumnLetter();
    }
    return null;
}