Epplus find column using column name

萝らか妹 提交于 2019-12-10 02:21:37

问题


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)


回答1:


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";



回答2:


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");



回答3:


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"



来源:https://stackoverflow.com/questions/39958798/epplus-find-column-using-column-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!