Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 704
Maro Avatar asked Oct 10 '16 12:10

Maro


3 Answers

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");
like image 79
Yehia Amer Avatar answered Nov 04 '22 00:11

Yehia Amer


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";
like image 42
Ernie S Avatar answered Nov 04 '22 00:11

Ernie S


You can extract the the values of the cells in the first row this way:

        using (ExcelPackage package = new ExcelPackage(new FileInfo(filePath)))
        {
            foreach (ExcelWorksheet worksheet in package.Workbook.Worksheets)
            {
                List<string> ColumnNames = new List<string>();
                for(int i = 1; i <= worksheet.Dimension.End.Column; i++)
                {
                    ColumnNames.Add(worksheet.Cells[1, i].Value.ToString()); // 1 = First Row, i = Column Number
                }
            }
        }

Then you can proceed to compare them according to your interests.

Just bear in mind that unlike with lists and arrays, the indexes of rows and columns start at "1" instead of "0"

like image 6
Innat3 Avatar answered Nov 04 '22 02:11

Innat3