Search code examples
c#datatableepplus

Epplus find column using column name


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)


Solution

  • Can do it with a little linq as well. So based off of your code snippet (might want to add some null-reference checks):

    var idx = sheet
        .Cells["1:1"]
        .First(c => c.Value.ToString() == "Birthdate")
        .Start
        .Column;
    
    sheet.Column(idx).Style.Numberformat.Format = "mm-dd-yy";