迭代匿名类型列表的对象属性

时间:2015-03-30 22:08:28

标签: c# .net anonymous-types epplus object-properties

我正在使用EPPlus创建一个"导出到Excel"帮手。这将基本上采用匿名列表并使用该列表填充电子表格。

我希望能够迭代列表对象的属性并确定哪个是datetime并适当地格式化该列。我在下面的代码工作,但有一个更简洁的方式来写这个 - 特别是我不依赖于从列表中拉出一个对象并操作该对象(即我获得属性类型)从列表本身)?

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

1 个答案:

答案 0 :(得分:3)

您可以使用T获取typeof(T).GetProperties()类型的属性。这也适用于匿名类型。

然后您不需要拉出第一项来检查其属性,也不必检查dataSet.Count > 0(如果您想允许空电子表格)。