먹는게 남는거다!

[C#] EPPlus로 엑셀 생성 시 필요없는 property 제거하기

C#, ASP.NET

EPPlus를 이용하여 POCO 클래스를 excel 파일에 출력할 때

Attribute를 이용하여 특정 property를 제외하는 방법



Attribute


1
public class EpplusIgnore : Attribute { }
cs



Epplus extensions


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static class Extensions
{
    public static ExcelRangeBase LoadFromCollectionFiltered<T>(this ExcelRangeBase @this, IEnumerable<T> collection) 
where T:class
    {
        MemberInfo[] membersToInclude = typeof(T)
            .GetProperties(BindingFlags.Instance | BindingFlags.Public)
            .Where(p=>!Attribute.IsDefined(p,typeof(EpplusIgnore)))
            .ToArray();
 
        return @this.LoadFromCollection<T>(collection, false
            OfficeOpenXml.Table.TableStyles.None, 
            BindingFlags.Instance | BindingFlags.Public, 
            membersToInclude);
    }
 
}
cs



Sample 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Person
{
    [EpplusIgnore]
    public int Key { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}
 
class Program
{
    static void Main(string[] args)
    {
        var demoData = new List<Person> { 
new Person { Key = 1, Age = 40, Name = "Fred" }, 
new Person { Key = 2, Name = "Eve", Age = 21 } 
};
 
        FileInfo fInfo = new FileInfo(@"C:\Temp\Book1.xlsx");
        using (var excel = new ExcelPackage())
        {
            var ws = excel.Workbook.Worksheets.Add("People");
            ws.Cells[11].LoadFromCollectionFiltered(demoData);
 
            excel.SaveAs(fInfo);
        }
    }
}
cs



출처: https://entityframework.net/knowledge-base/25603492/ignoring-properties-when-calling-loadfromcollection-in-epplus