Epplus find column using column name

Maro picture Maro · Oct 10, 2016 · Viewed 19k times · Source

I have excel sheet created dynamically, i would like to format some columns as date however i don't know the index of these columns in advance i only know the header title.

1- I load the excel from DataTable

var templateXls = new ExcelPackage();
        var sheet = templateXls.Workbook.Worksheets.Add(parameters.ReportName);

        sheet.Cells["A1"].LoadFromDataTable(myDataTable, true);

Now how can i format for example column with name "Birthdate" to be short-date field? the column can be in any index depends on user selection also there is a possibility that the column is not generated. (if the user doesn't include it)

Answer

Yehia Amer picture Yehia Amer · Dec 12, 2016

You may also use extention Method like this:

public static class EpPlusExtensionMethods
{
    public static int GetColumnByName(this ExcelWorksheet ws, string columnName)
    {
        if (ws == null) throw new ArgumentNullException(nameof(ws));
        return ws.Cells["1:1"].First(c => c.Value.ToString() == columnName).Start.Column;
    }
}

and Use it :

int columnId = ws.GetColumnByName("Birthdate");