WeihanLi.Npoi 3.3.0

Prefix Reserved
dotnet add package WeihanLi.Npoi --version 3.3.0
                    
NuGet\Install-Package WeihanLi.Npoi -Version 3.3.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="WeihanLi.Npoi" Version="3.3.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="WeihanLi.Npoi" Version="3.3.0" />
                    
Directory.Packages.props
<PackageReference Include="WeihanLi.Npoi" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add WeihanLi.Npoi --version 3.3.0
                    
#r "nuget: WeihanLi.Npoi, 3.3.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package WeihanLi.Npoi@3.3.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=WeihanLi.Npoi&version=3.3.0
                    
Install as a Cake Addin
#tool nuget:?package=WeihanLi.Npoi&version=3.3.0
                    
Install as a Cake Tool

WeihanLi.Npoi

WeihanLi.Npoi WeihanLi.Npoi Latest NuGet Downloads

Build Status

Azure Pipeline Build Status Github Build Status

Introduction

NPOI extensions based on target framework netstandard2.0.

WeihanLi.Npoi provides a powerful and easy-to-use toolkit for working with Excel and CSV files in .NET applications. It offers:

  • Simple API: Intuitive extension methods for common import/export operations
  • Flexible Configuration: Support for both Attribute-based and FluentAPI configuration
  • High Performance: Optimized for handling large datasets efficiently
  • Rich Features: Advanced capabilities like template export, multi-sheet support, and shadow properties
  • CSV Support: Full support for CSV file operations alongside Excel

Core Features

📥 Data Import

  • Import Excel files to List<TEntity> or IEnumerable<TEntity>
  • Import Excel files to DataTable
  • Import CSV files to entities or DataTable
  • Support for custom header rows and sheet selection
  • Automatic type conversion and data mapping

📤 Data Export

  • Export IEnumerable<TEntity> or DataTable to Excel files (.xls/.xlsx)
  • Export data to Excel byte arrays or streams
  • Export to CSV files or byte arrays
  • Template-based export with placeholders for complex layouts
  • Multi-sheet export in a single workbook

⚙️ Configuration Options

  • Attribute Configuration: Simple decoration with [Column] and [Sheet] attributes
  • FluentAPI Configuration: Powerful and flexible configuration with fluent syntax (Recommended)
  • Custom column mapping, formatting, and transformations
  • Support for shadow properties (columns not in the model)

🎨 Advanced Capabilities

  • InputFormatter/OutputFormatter: Transform data during import/export operations
  • ColumnInputFormatter/ColumnOutputFormatter: Column-specific data transformations
  • CellReader: Custom cell reading logic
  • Template Export: Export data based on pre-designed Excel templates
  • Multi-Sheet Support: Handle multiple sheets in a single workbook
  • Shadow Properties: Define additional export columns not present in your models
  • Auto Column Width: Automatic column width adjustment
  • Freeze Panes: Set freeze panes for better data viewing
  • Filters: Add auto-filters to your Excel sheets

GetStarted

Installation
dotnet add package WeihanLi.Npoi
Quick Start
  1. Export list/dataTable to Excel/csv

    var entities = new List<Entity>();
    
    // Export to Excel file
    entities.ToExcelFile(string excelPath);
    
    // Export to Excel bytes
    entities.ToExcelBytes(ExcelFormat excelFormat);
    
    // Export to CSV file
    entities.ToCsvFile(string csvPath);
    
    // Export to CSV bytes
    entities.ToCsvBytes();
    
  2. Import Excel/csv to List

    // Read Excel first sheet content to List<T>
    var entityList = ExcelHelper.ToEntityList<T>(string excelPath);
    
    // Read Excel first sheet content to IEnumerable<T>
    var entityList = ExcelHelper.ToEntities<T>(string excelPath);
    
    // Read Excel specific sheet content to List<T>
    // You can customize header row index via sheet attribute or fluent api HasSheet
    var entityList1 = ExcelHelper.ToEntityList<T>(string excelPath, int sheetIndex);
    
    // Import CSV to List<T>
    var entityList2 = CsvHelper.ToEntityList<T>(string csvPath);
    var entityList3 = CsvHelper.ToEntityList<T>(byte[] csvBytes);
    
  3. Import Excel/csv to DataTable

    // Read Excel to DataTable directly, by default read the first sheet content
    var dataTable = ExcelHelper.ToDataTable(string excelPath);
    
    // Read Excel workbook's specific sheet to DataTable
    var dataTableOfSheetIndex = ExcelHelper.ToDataTable(string excelPath, int sheetIndex);
    
    // Read Excel with custom header row index
    var dataTableOfSheetIndex = ExcelHelper.ToDataTable(string excelPath, int sheetIndex, int headerRowIndex);
    
    // Read Excel to DataTable using mapping relations and settings from typeof(T)
    var dataTableT = ExcelHelper.ToDataTable<T>(string excelPath);
    
    // Read CSV file data to DataTable
    var dataTable1 = CsvHelper.ToDataTable(string csvFilePath);
    

More Api documentation: https://weihanli.github.io/WeihanLi.Npoi/api/WeihanLi.Npoi.html

Configuration

1. Using Attributes

Add ColumnAttribute on the properties of your entity for export or import operations.

Add SheetAttribute on the entity to configure sheet settings. You can set the StartRowIndex as needed (default is 1).

Example:

[Sheet(SheetName = "TestSheet", SheetIndex = 0, AutoColumnWidthEnabled = true)]
public class TestEntity
{
    [Column("ID", Index = 0)]
    public int PKID { get; set; }

    [Column("Bill Title", Index = 1)]
    public string BillTitle { get; set; }

    [Column("Bill Details", Index = 2)]
    public string BillDetails { get; set; }

    [Column("Created By", Index = 3)]
    public string CreatedBy { get; set; }

    [Column("Created Time", Index = 4, Formatter = "yyyy-MM-dd HH:mm:ss")]
    public DateTime CreatedTime { get; set; }
    
    [Column(IsIgnored = true)]
    public string InternalNote { 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("WeChat OpenID")]
    public string WechatOpenId { get; set; }

    [Column("Is Active")]
    public bool IsActive { get; set; }
}

FluentAPI provides greater flexibility and more powerful configuration options.

Example:

var setting = FluentSettings.For<TestEntity>();

// Excel document settings
setting.HasAuthor("WeihanLi")
    .HasTitle("WeihanLi.Npoi test")
    .HasDescription("WeihanLi.Npoi test")
    .HasSubject("WeihanLi.Npoi test");

// Sheet configuration (sheetIndex, sheetName, startRowIndex, autoColumnWidth)
setting.HasSheetConfiguration(0, "SystemSettingsList", 1, true);

// Apply filters and freeze panes
// setting.HasFilter(0, 1).HasFreezePane(0, 1, 2, 1);

// Configure individual properties
setting.Property(_ => _.SettingId)
    .HasColumnIndex(0);

setting.Property(_ => _.SettingName)
    .HasColumnTitle("SettingName")
    .HasColumnIndex(1);

setting.Property(_ => _.DisplayName)
    .HasOutputFormatter((entity, displayName) => $"AAA_{entity.SettingName}_{displayName}")
    .HasInputFormatter((entity, originVal) => originVal.Split(new[] { '_' })[2])
    .HasColumnTitle("DisplayName")
    .HasColumnIndex(2);

setting.Property(_ => _.SettingValue)
    .HasColumnTitle("SettingValue")
    .HasColumnIndex(3);

setting.Property(_ => _.CreatedTime)
    .HasColumnTitle("CreatedTime")
    .HasColumnIndex(4)
    .HasColumnWidth(10)
    .HasColumnFormatter("yyyy-MM-dd HH:mm:ss");

setting.Property(_ => _.CreatedBy)
    .HasColumnInputFormatter(x => x += "_test")
    .HasColumnIndex(5)
    .HasColumnTitle("CreatedBy");

setting.Property(x => x.Enabled)
    .HasColumnInputFormatter(val => "Enabled".Equals(val))
    .HasColumnOutputFormatter(v => v ? "Enabled" : "Disabled");

// Shadow property - define a column that doesn't exist in the model
setting.Property("HiddenProp")
    .HasOutputFormatter((entity, val) => $"HiddenProp_{entity.PKID}");

// Ignore specific properties
setting.Property(_ => _.PKID).Ignored();
setting.Property(_ => _.UpdatedBy).Ignored();
setting.Property(_ => _.UpdatedTime).Ignored();

Advanced Features

Template-based Export

Export data based on pre-designed Excel templates with placeholder support:

entities.ToExcelFileByTemplate(
    templatePath: "path/to/template.xlsx",
    excelPath: "path/to/output.xlsx",
    extraData: new { Author = "WeihanLi", Title = "Export Result" }
);

Learn more: Template Export Documentation

Multi-Sheet Export

Export multiple collections to different sheets in a single workbook:

var workbook = ExcelHelper.PrepareWorkbook(ExcelFormat.Xlsx);
workbook.ImportData(collection1, sheetIndex: 0);
workbook.ImportData(collection2, sheetIndex: 1);
workbook.WriteToFile("multi-sheets.xlsx");

Learn more: Multi-Sheet Documentation

Shadow Properties

Define additional export columns that don't exist in your model:

var settings = FluentSettings.For<TestEntity>();
settings.Property("Employee ID")
    .HasOutputFormatter((entity, val) => $"{entity.UserFields[2].Value}");
settings.Property("Department")
    .HasOutputFormatter((entity, val) => $"{entity.UserFields[1].Value}");

Learn more: Shadow Property Documentation

Documentation

More

see some articles here: https://weihanli.github.io/WeihanLi.Npoi/articles/intro.html

more usage:

<details> <summary>Get a workbook</summary>

// load excel workbook from file
var workbook = LoadExcel(string excelPath);

// prepare a workbook accounting to excelPath
var workbook = PrepareWorkbook(string excelPath);

// prepare a workbook accounting to excelPath and custom excel settings
var workbook = PrepareWorkbook(string excelPath, ExcelSetting excelSetting);

// prepare a workbook whether *.xls file
var workbook = PrepareWorkbook(bool isXls);

// prepare a workbook whether *.xls file and custom excel setting
var workbook = PrepareWorkbook(bool isXlsx, ExcelSetting excelSetting);

</details>

<details> <summary>Rich extensions</summary>

List<TEntity> ToEntityList<TEntity>([NotNull]this IWorkbook workbook)

DataTable ToDataTable([NotNull]this IWorkbook workbook)

ISheet ImportData<TEntity>([NotNull] this ISheet sheet, DataTable dataTable)

int ImportData<TEntity>([NotNull] this IWorkbook workbook, IEnumerable<TEntity> list,
            int sheetIndex)

int ImportData<TEntity>([NotNull] this ISheet sheet, IEnumerable<TEntity> list)

int ImportData<TEntity>([NotNull] this IWorkbook workbook, [NotNull] DataTable dataTable,
            int sheetIndex)

ToExcelFile<TEntity>([NotNull] this IEnumerable<TEntity> entityList,
            [NotNull] string excelPath)

int ToExcelStream<TEntity>([NotNull] this IEnumerable<TEntity> entityList,
            [NotNull] Stream stream)

byte[] ToExcelBytes<TEntity>([NotNull] this IEnumerable<TEntity> entityList)

int ToExcelFile([NotNull] this DataTable dataTable, [NotNull] string excelPath)

int ToExcelStream([NotNull] this DataTable dataTable, [NotNull] Stream stream)

byte[] ToExcelBytes([NotNull] this DataTable dataTable)

byte[] ToExcelBytes([NotNull] this IWorkbook workbook)

int WriteToFile([NotNull] this IWorkbook workbook, string filePath)

object GetCellValue([NotNull] this ICell cell, Type propertyType)

T GetCellValue<T>([NotNull] this ICell cell)

void SetCellValue([NotNull] this ICell cell, object value)

byte[] ToCsvBytes<TEntity>(this IEnumerable<TEntity> entities, bool includeHeader)

ToCsvFile<TEntity>(this IEnumerable<TEntity> entities, string filePath, bool includeHeader)

void ToCsvFile(this DataTable dt, string filePath, bool includeHeader)

byte[] ToCsvBytes(this DataTable dt, bool includeHeader)

</details>

Samples

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Acknowledgements

  • Thanks to all the contributors and users of this project
  • Thanks to NPOI for the excellent Excel library
  • Thanks to FluentExcel for the FluentAPI inspiration
  • Thanks to JetBrains for the free Rider license

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Contact & Support

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on WeihanLi.Npoi:

Repository Stars
WeihanLi/DbTool
数据库工具,根据表结构文档生成创建表sql,根据数据库表信息导出Model和表结构文档,根据文档生成数据库表,根据已有Model文件生成创建数据库表sql
Version Downloads Last Updated
3.3.0 175 1/28/2026
3.3.0-preview-20260128-003644 90 1/28/2026
3.3.0-preview-20260125-132000 113 1/25/2026
3.2.0 498 11/17/2025
3.2.0-preview-20251116-150124 255 11/16/2025
3.1.0 1,135 4/1/2025
3.1.0-preview-20250331-152213 248 3/31/2025
3.0.0 1,457 12/18/2024
3.0.0-preview-20241218-005537 183 12/18/2024
3.0.0-preview-20241216-160044 200 12/16/2024
2.5.0 1,929 7/29/2024
2.4.2 35,502 8/10/2022
2.4.2-preview-20220810-082616 346 8/10/2022
2.4.1 662 8/10/2022
2.4.0 642 8/9/2022
2.4.0-preview-20220809-141016 341 8/9/2022
2.3.0 6,541 6/7/2022
2.2.0 1,217 5/12/2022
2.1.0 882 4/24/2022
2.1.0-preview-20220423-164958 352 4/23/2022
Loading failed