I\'m using EPPlus
to generate Excel
files, in DAL I\'m populating DataTable
, filling data into table, and passing table to Presentation La
If your columns are likely to move around (as we know end-users tend to be fickle) or you just have many date columns scattered across your spreadsheet, it would be helpful to write something a little more generic. Here is what I just wrote. It finds the position of all DateTime types in my POCO and creates a list that it then uses to set the column formatting. Remember data tables are zero based and Excel is not.
ws.Cells.LoadFromDataTable(tbl, true);
var dPos = new List();
for (var i = 0; i < tbl.Columns.Count; i++)
if (tbl.Columns[i].DataType.Name.Equals("DateTime"))
dPos.Add(i);
foreach (var pos in dPos)
{
ws.Column(pos+1).Style.Numberformat.Format = "mm/dd/yyyy hh:mm:ss AM/PM";
}
If you are doing more than one datatable, you'll probably want to refactor it off into a function.
And here is a freebie... I can't take credit for this code. It takes a POCO list and turns it into a data table. It has made my life easier on a number of occasions having it in my 'toolkit'. Enjoy.
public DataTable ConvertToDataTable(IList data)
{
var properties =
TypeDescriptor.GetProperties(typeof(T));
var table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
var row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}