WeihanLi.Npoi 支持 ShadowProperty 了
WeihanLi.Npoi 支持?ShadowProperty?了
Intro
在 EF 里有個 ShadowProperty (陰影屬性/影子屬性)的概念,你可以通過 FluentAPI 的方式來定義一個不在 .NET model 里定義的屬性,只能通過 EF 里的 ChangeTracker 來操作這種屬性。
在導出 Excel 的時候,可能希望導出的列并不是都定義好在我們的 model 中的,有的可能只是想增加一列導出某個屬性中的嵌套屬性之中的某一個屬性值,或者我就是單純的想多定義一列,而這個時候可能 model 是別的地方寫死的,不方便改。
于是 WeihanLi.Npoi 從 1.6.0 版本開始支持 ShadowProperty ,將 EF 里的 ShadowProperty 引入到 excel 導出里,目前來說 ShadowProperty 是不可寫的,讀取的話也只是返回一個類型的默認值,不支持 ChangeTracker,不支持改。
使用示例
來看一個簡單使用示例:(示例來源于網友提出的這個issue:https://github.com/WeihanLi/WeihanLi.Npoi/issues/51)
using System; using System.Collections.Generic; using System.IO; using WeihanLi.Npoi; namespace NpoiTest {public class Program{public static void Main(string[] args){var settings = ExcelHelper.SettingFor<TestEntity>();settings.Property(x => x.Name).HasColumnIndex(0);// settings.Property(x => x.UserFields)// .HasOutputFormatter((entity, value) => $"{value[0].Value},{value[2].Value}")// .HasColumnTitle("姓名,工號")// .HasColumnIndex(1);settings.Property(x=>x.UserFields).Ignored();settings.Property("工號").HasOutputFormatter((entity,val)=> $"{entity.UserFields[2].Value}");settings.Property("部門").HasOutputFormatter((entity,val)=> $"{entity.UserFields[1].Value}");var data = new List<TestEntity>(){new TestEntity(){Name = "xiaoming",TotalScore = 100,UserFields = new UserField[]{new UserField(){Name = "姓名",Value = "xaioming",},new UserField(){Name = "部門",Value = "1212"},new UserField(){Name = "工號",Value = "121213131"},}}};data.ToExcelFile($@"{Directory.GetCurrentDirectory()}\output.xls");Console.WriteLine("complete.");}private class TestEntity{public string Name { get; set; }public UserField[] UserFields { get; set; }public int TotalScore { get; set; }}private class UserField{public string Fid { get; set; }public string Name { get; set; }public string Value { get; set; }}} }導出效果如下:
可以看到,我們為導出的 Excel 增加在原本的 Model 里沒有定義的兩列,借助于此,我們可以更靈活的定制要導出的內容
More
快來體驗吧,歡迎反饋,歡迎 issue
Reference
https://docs.microsoft.com/en-us/ef/core/modeling/shadow-properties
https://docs.microsoft.com/zh-cn/ef/core/modeling/shadow-properties
https://github.com/WeihanLi/WeihanLi.Npoi/issues/51
https://github.com/WeihanLi/WeihanLi.Npoi
總結
以上是生活随笔為你收集整理的WeihanLi.Npoi 支持 ShadowProperty 了的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (译)An introduction t
- 下一篇: 使用ASP.NET Core 3.x 构