讓 .Net 更方便的導入導出Excel
Intro
因為前一段時間需要處理一些 excel 數據,主要是導入/導出操作,將 Excel 數據轉化為對象再用程序進行處理和分析,沒有找到比較滿意的庫,於是就自己造了一個輪子,屏蔽掉了 xlsx 與 xls 的差別,屏蔽了 Npoi 操作 Excel 的細節,提供簡單容易上手的 api。完整的 API 列表請查看:https://weihanli.github.io/WeihanLi.Npoi/docs/api/WeihanLi.Npoi.html
導入/導出
添加 nuget 包引用 WeihanLi.Npoi
根據 excel 文件獲取一個 IWorkbook
對象,支持 *.xls/*.xlsx
IWorkbook workbook = ExcelHelper.LoadExcel("excelFilePath");
將 Excel 文件的第一個 sheet 里的內容轉成 list 對象
List<TEntity> entityList = ExcelHelper.ToEntityList<TEntity>("excelFilePath");
將 Excel 文件的第一個 sheet 里的內容轉成 DataTable 對象
DataTable dataTable = ExcelHelper.ToDataTable("excelFilePath");
將 list 對象導出到 Excel 字節數組
List<TEntity> entityList = ExcelHelper.ToEntityList<TEntity>("excelFilePath");
entityList.ToExcelBytes();
將 list 對象導出到 Excel 文件
List<TEntity> entityList = ExcelHelper.ToEntityList<TEntity>("excelFilePath");
entityList.ToExcelFile("excelFilePath");
自定義配置
默認的導入導出是按照屬性名為導出的列名稱的,如果不能滿足或者想要自定義某些屬性不導出或設置導出順序,可以通過配置實現
提供了兩種配置方式,一種是使用 Attribute 方式來配置,第二種是使用 FluentAPI 方式配置(推薦,對代碼無侵入性)
-
Attributes
在要導入導出的屬性上設置
ColumnAttribute
來自定義導出的列名稱或排序或忽略添加
SheetAttribute
來設置導出的excel sheet名稱等for example:
public class TestEntity { [Column("Id")] public int PKID { get; set; } [Column("Bill Title")] public string BillTitle { get; set; } [Column("Bill Details")] public string BillDetails { get; set; } [Column("CreatedBy")] public string CreatedBy { get; set; } [Column("CreatedTime")] public DateTime CreatedTime { get; set; } } public class TestEntity1 { [Column("Username")] public string Username { get; set; } [Column(IsIgnored = true)] public string PasswordHash { get; set; } [Column("Amount")] public decimal Amount { get; set; } = 1000M; [Column("WechatOpenId")] public string WechatOpenId { get; set; } [Column("IsActive")] public bool IsActive { get; set; } }
-
FluentApi (Recommend)
var setting = ExcelHelper.SettingFor<TestEntity>(); // ExcelSetting setting.HasAuthor("WeihanLi") .HasTitle("WeihanLi.Npoi test") .HasDescription("") .HasSubject(""); setting.HasSheetConfiguration(0, "System Settings"); setting.HasFilter(0, 1) .HasFreezePane(0, 1, 2, 1); setting.Property(_ => _.SettingId) .HasColumnIndex(0); setting.Property(_ => _.SettingName) .HasColumnTitle("SettingName") .HasColumnIndex(1); setting.Property(_ => _.DisplayName) .HasColumnFormatter((entity, displayName) => $"AAA_{entity.SettingName}_{displayName}") .HasColumnTitle("DisplayName") .HasColumnIndex(2); setting.Property(_ => _.SettingValue) .HasColumnTitle("SettingValue") .HasColumnIndex(3); setting.Property(_ => _.CreatedTime) .HasColumnTitle("CreatedTime") .HasColumnIndex(5) .HasColumnFormatter("yyyy-MM-dd HH:mm:ss"); setting.Property(_ => _.CreatedBy) .HasColumnIndex(4) .HasColumnTitle("CreatedBy"); setting.Property(_ => _.UpdatedBy).Ignored(); setting.Property(_ => _.UpdatedTime).Ignored(); setting.Property(_ => _.PKID).Ignored();
More
Contact
如果使用過程中有遇到什么問題,歡迎與我聯系。
Contact me: weihanli@oulook.com