I have a problem with date format, I have a generic class that reads property and property type.
EPPlus generates for a date column the good format but the other it is not.
public class ExcelHelper
{
public static byte[] GenerateXls<T>(List<T> dataSource, string sheetName)
{
using (var pck = new ExcelPackage())
{
var modelProperties = typeof(T).GetProperties();
Type typeNullDatetime = typeof(DateTime?);
Type typeDateTime = typeof(DateTime);
Type typeDecimal = typeof(decimal);
Type typeNullDecimal = typeof(decimal?);
var ws = pck.Workbook.Worksheets.Add(sheetName);
ws.Cells[1, 1].LoadFromCollection(dataSource, true, OfficeOpenXml.Table.TableStyles.Light1);
for (var j = 0; j < modelProperties.Length; j++)
{
if (modelProperties[j].PropertyType == typeNullDatetime
&& DateTimeFormatInfo.CurrentInfo != null)
ws.Column(j).Style.Numberformat.Format =
DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
if (modelProperties[j].PropertyType == typeDateTime)
if (DateTimeFormatInfo.CurrentInfo != null)
ws.Column(j).Style.Numberformat.Format =
DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
if (modelProperties[j].PropertyType == typeDecimal)
ws.Column(j).Style.Numberformat.Format = "0.00";
if (modelProperties[j].PropertyType == typeNullDecimal)
ws.Column(j).Style.Numberformat.Format = "0.00";
}
ws.Cells.AutoFitColumns();
return pck.GetAsByteArray();
}
}
}
var result = ExcelHelper.GenerateXls(dtos, "data");
the genertated excel for a class containing these two properties :
public DateTime IssueDate { get; set; }
public DateTime DeadlineDate { get; set; }
Issue Date Deadline Date
25/06/2019 43641
25/06/2019 43641
05/06/2019 43622
27/05/2019 43612
24/04/2019 43579
15/04/2019 43570
In EPPlus column and rows are not zero-based indices but 1-based. So the first column of the first row has Row=1 and Column=1. you need to change the loop like below
...
for (var j = 1; j <= modelProperties.Length; j++)
...
or
...
ws.Column(j+1)
...