Ped*_*ino 3 c# epplus epplus-4
我正在使用方法 LoadFromCollection 用列表填充 excel。但是,excel 列需要有一定的顺序才能为用户提供更好的上下文,所以我试图找出如何实现这一点。
我的一种选择是在类中设置参数的顺序,但我避免这样做,因为其他人可以更改他们的顺序,这会影响我的代码。
我的第二个选择是使用 Linq:
var orderedColumns = (from p in myList
select new { p.Name, p.Age, ...}).ToList();
Run Code Online (Sandbox Code Playgroud)
这样我也可以定义列顺序,但我不喜欢在我已经准备好使用列表时必须创建匿名的想法(我也丢失了我为类定义的 DisplayNameAttribute)。
你们有什么想法吗?也许我可以使用 MemberInfo[]?
我已经找到了一个解决方案,我将与大家分享。
public class MyClass
{
[DataMember(Order = 1)]
public string PropertyA;
[DataMember(Order = 2)]
public int PropertyB
[DataMember(Order = 0)]
public bool propertyC
}
Run Code Online (Sandbox Code Playgroud)
使用这样的代码,如果我有一个List<MyClass>并使用LoadFromCollection()来自 Epplus 的结果 excel 将按照它们在类中出现的顺序显示列:
PropertyA | PropertyB | PropertyC
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题,我们可以做到以下几点:
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());
Run Code Online (Sandbox Code Playgroud)
生成的 excel 将显示此列顺序:
PropertyC | PropertyA | PropertyB
Run Code Online (Sandbox Code Playgroud)
注意:只有具有该[DataMember(Order = x)]属性的列才会显示在 excel 上,但我也想实现这一点,因为我不想在 excel 中显示我班上的某些列。
感谢@Sanjay 提及 DataMember 属性。