我正在使用 EPPlus 创建一个“导出到 Excel”助手。这基本上将采用一个匿名列表并使用该列表来填充电子表格。
我希望能够遍历列表对象的属性并确定哪个是 adatetime
并适当地格式化该列。我在下面的代码有效,但是是否有更简洁的方法来编写它-特别是在我不依赖于从列表中提取对象并对该对象进行操作的情况下(即,我从列表本身获取属性类型)?
private static string[] columnIndex = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z".Split(',');
private static ExcelWorksheet CreateAndFormatWorksheet<T>(OfficeOpenXml.ExcelPackage pck, List<T> dataSet)
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Monet_Export_" + DateTime.Now.ToString());
ws.Cells["A1"].LoadFromCollection(dataSet, true);
if (dataSet.Count > 0)
{
// Pull first list item to determine so we have something to iterate over below
dynamic first = dataSet[0];
// List count == upper row count for the spreadsheet
string rowCount = dataSet.Count.ToString();
int i = 0;
foreach (PropertyInfo info in first.GetType().GetProperties())
{
if (info.PropertyType == typeof(DateTime))
{
string column = columnIndex[i];
string indexer = column + "2:" + column + rowCount;
ws.Cells[indexer].Style.Numberformat.Format = "mm/dd/yyyy";
}
else if (info.PropertyType == typeof (int))
{
string column = columnIndex[i];
string indexer = column + "2:" + column + rowCount;
ws.Cells[indexer].Style.Numberformat.Format = "@";
}
i++;
}
}
return ws;
}