WeihanLi.Npoi 支持 ShadowProperty 了
Intro
在 EF 里有個 ShadowProperty (陰影屬性/影子屬性)的概念,你可以通過 FluentAPI 的方式來定義一個不在 .NET model 里定義的屬性,只能通過 EF 里的 Change Tracker 來操作這種屬性,
在匯出 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 = https://www.cnblogs.com/weihanli/p/new List()
{
new TestEntity()
{
Name ="xiaoming",
TotalScore = 100,
UserFields = new UserField[]
{
new UserField()
{
Name = "姓名",
Value = "https://www.cnblogs.com/weihanli/p/xaioming",
},
new UserField()
{
Name = "部門",
Value = "https://www.cnblogs.com/weihanli/p/1212"
},
new UserField()
{
Name = "工號",
Value = "https://www.cnblogs.com/weihanli/p/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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/91523.html
標籤:C#
