Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

closedxml

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?

like image 320
leora Avatar asked Apr 11 '15 06:04

leora


People also ask

How do you create a datatype for a column in ClosedXML?

ClosedXML sets the data type for all cells in the column, down to the maximum (row 1 million or so). Use this to only set the data type for the used cells in the column: ws. Column(1).

Can ClosedXML read XLS file?

ClosedXML is a . NET library for reading, manipulating and writing Excel 2007+ (. xlsx, . xlsm) files.


1 Answers

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;
}
like image 168
christophano Avatar answered Sep 27 '22 22:09

christophano