c# - Epplus - LoadFromCollection 和列顺序

标签 c# epplus epplus-4

我正在使用 LoadFromCollection 方法用列表填充 excel。但是,Excel 列需要有一定的顺序才能为用户提供更好的上下文,所以我正在尝试找出如何实现这一点。

我有一个选择是在类中设置参数的顺序,但我避免这样做,因为其他人可以更改他们的顺序,这会影响我的代码。

我的第二个选择是使用 Linq:

var orderedColumns = (from p in myList 
                     select new { p.Name, p.Age, ...}).ToList();

这样我也可以定义列顺序,但我不喜欢在我已经准备好要使用的列表时必须创建一个匿名的想法(我也丢失了我为类定义的 DisplayNameAttribute) .

你们有什么想法吗?也许我可以使用 MemberInfo[]?

最佳答案

我找到了一个解决方案,我将与大家分享。

public class MyClass
{
   [DataMember(Order = 1)]
   public string PropertyA;

   [DataMember(Order = 2)]
   public int PropertyB

   [DataMember(Order = 0)]
   public bool propertyC
}

使用这样的代码,如果我有 List<MyClass>并使用 LoadFromCollection()从 Epplus 生成的 excel 将按照它们在类中出现的顺序显示列:

PropertyA | PropertyB | PropertyC

为了解决这个问题,我们可以做到以下几点:

var orderedProperties = (from property in typeof(MyClass).GetProperties()
                         where Attribute.IsDefined(property, typeof(DataMemberAttribute))
                         orderby ((DataMemberAttribute)property
                                  .GetCustomAttributes(typeof(DataMemberAttribute), false)
                                  .Single()).Order
                         select property);

var ws = p.Workbook.Worksheets.Add("MySheet");
ws.Cells[1, 1].LoadFromCollection(myClassCollection, true, OfficeOpenXml.Table.TableStyles.Light1
   ,System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public
   ,orderedProperties.ToArray());

生成的 excel 将显示此列的顺序:

PropertyC | PropertyA | PropertyB

注意:只有带有 [DataMember(Order = x)] 的列属性将显示在 excel 中,但我也想实现这一点,因为我的类(class)中有一些列我不想在 excel 中显示。

感谢@Sanjay 提到 DataMember 属性。

关于c# - Epplus - LoadFromCollection 和列顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52557959/

相关文章:

c# - EPPlus - 在删除行后向上移动行

c# - 如何确保文件从我的工作目录复制到 bin/Debug rsp。垃圾桶/释放?

c# - 开始现代游戏编程和应用程序编程的最佳方式是什么?

c# - 使用 EPPLUS c# 在一页上适合所有列

c# - 使用 Epplus 的 Excel 时间格式

c# - 在 EPPlus 中更改线条系列的颜色

c# - 绘制两条相交的线,需要使用 directx 在 c# 中找到相交点吗?

c# - 发送邮件 Asp.Net 时出现 "Authentication failed"错误

c# - EPPlus:数据透视表列中的值

c# - EPPlus 折线图无法将轴与刻度线对齐