PropertyDescriptor与PropertyInfo并导出到Excel

时间:2016-06-30 13:41:10

标签: c#

我的目标是将MVC视图模型导出到Excel中。我想只导出设置了Display属性的列。

我成功提取属性以填充列名:

        var type = typeof(MyViewModel);
        var propertyMetaData = type.GetProperties()
            .Select(property => property.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault() as DisplayAttribute)
            .Where(attribute => attribute != null)
            .ToList();

        DataTable table = new DataTable();
        foreach (var prop in propertyMetaData)
            table.Columns.Add(prop.Name);

我的问题是当我试图填充数据时:

        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(MyViewModel));
        foreach (MyViewModel item in lst_VM)
        {
            DataRow row = table.NewRow();

            foreach (PropertyDescriptor prop in properties)
                if ((prop.GetType().GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault() as DisplayAttribute) != null)
                {
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;

                    table.Rows.Add(row);
                }
        }

问题是上面的代码选择了所有属性,并返回该列不属于表的错误。

我的视图模型如下所示:

    [Display(Name = "Application Name")]
    public string ApplicationName { get; set; }
    [Required(ErrorMessage = "Make is required.")]
    public int MakeID { get; set; }
    [Display(Name = "Make")]
    public string Make { get; set; }

我只想导出那些设置了[显示(姓名="")]

1 个答案:

答案 0 :(得分:0)

经过10个小时的搜索和尝试不同的事情,我终于找到了我需要的东西:

        foreach (MyViewModel item in lst_Host_VM)
        {
            DataRow row = table.NewRow();

            var test = typeof(MyViewModel).GetProperties()
                .Where(p => p.IsDefined(typeof(DisplayAttribute), false))
                .Select(p => new
                {
                    PropertyName = p.Name,
                    p.GetCustomAttributes(typeof(DisplayAttribute), false).Cast<DisplayAttribute>().Single().Name,
                    Value = p.GetValue(item)
                });

            foreach (var itm in test)
            {
                row[itm.Name] = itm.Value;
            }

            table.Rows.Add(row);
        }

如果您认为可以更温和的方式完成,请告诉我。

相关问题