Home » excel » c# 4.0 – How to loop through and read the column headers in excel using epplus

c# 4.0 – How to loop through and read the column headers in excel using epplus

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m using epplus to read an excel file, I want to loop through each rows and each column and look for the column header to check against a collection and read the cell value if it matches. I’m new to epplus and couldn’t find any reference to do something like this. I have looked into the similar question in this link, but I don’t have something that loops through column headers.

Is there a possibility for doing this? Any help is much appreciated.

Thanks!

How to&Answers:

If you want to find a column in the Excel file that matches the name you specify you can use this function:

    public string FindColumnAddress(ExcelWorksheet sheet, string columnName)
    {

        int totalRows = sheet.Dimension.End.Row;
        int totalCols = sheet.Dimension.End.Column;
        var range = sheet.Cells[1, 1, 1, totalCols];
        for (int i = 1; i <= totalCols; i++)
        {
            if (range[1, i].Address != "" && range[1, i].Value != null && range[1, i].Value.ToString() == columnName)
                return range[1, i].Address;

        }
        return null;
    }

It will return the address of the column header.
You can change it to return i as the index of the column.

Answer:

Or if you prefer a solution using Linq:

    /// <summary>
    /// Get 1 based column number of first column with 'columnName' as column header
    /// </summary>
    /// <param name="sheet"></param>
    /// <param name="columnName">Column name to find</param>
    /// <returns>1 based column number if found or null if column not found</returns>
    public int? FindColumnAddress(ExcelWorksheet sheet, string columnName)
    {

        int totalCols = sheet.Dimension.End.Column;
        var header = sheet.Cells[1, 1, 1, totalCols].ToList();

        var idx = header.IndexOf(header.FirstOrDefault(hdritm => hdritm.Text == columnName));

        return idx < 0 ? (int?)null : idx + 1;
    }

Note: If you are retrieving many column header locations, you might want to generate the “header” list and then use the Linq query to retrieve each column number w/o having to rebuild the list for every search.

I found suggestion to use IndexOf here:

Get List<> element position in c# using LINQ