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)
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");
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";
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With