I'm using the method LoadFromCollection to fill an excel with a List. However, the excel columns need to have a certain order to provide a better context for the user, so I'm trying to find out how to accomplish this.
One option I've is to set the order of the parameters inside the class, but I'm avoiding this because someone else can change their order and that will affect my code.
The second option I've is to use Linq:
var orderedColumns = (from p in myList
select new { p.Name, p.Age, ...}).ToList();
This way I can also define the column order, but I don't like the idea of having to create an anonymous when I already have the list ready to be used (I also lose the DisplayNameAttribute that I defined for the class).
Do you guys have any ideas? Perhaps I could use MemberInfo[]?
I've found a solution that I'll share with you guys.
With the code like this, if I have a
List<MyClass>
and use theLoadFromCollection()
from Epplus the resulting excel will show the columns in the order to which they appear in the class:To solve this problem, we can do the following:
The resulting excel will show this columns order:
Note: only the columns with the
[DataMember(Order = x)]
attribute will show up on the excel, but I also wanted to achieve this because there are some columns of my class that I don't want to show in the excel.Credits to @Sanjay for mentioning the DataMember attribute.