百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
E

excel-mapper

> 编程语言
开源

流畅地将 Excel 行映射到 C# 对象

179 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

流畅地将 Excel 行映射到 C# 对象

ExcelMapper

A powerful, flexible .NET library for mapping Excel spreadsheet data to strongly-typed C# objects. ExcelMapper provides an intuitive fluent API with extensive customization options, robust type conversion, and comprehensive error handling.

Built on top of ExcelDataReader for reliable Excel file parsing.

Features

  • ✨ Automatic mapping - Maps properties by convention with zero configuration
  • Type-safe fluent API - Strongly-typed mapping configuration using expressions
  • Extensive customization - Custom converters, transformers, and fallback strategies
  • Multiple mapping strategies - One-to-one, many-to-one, collections, dictionaries
  • ️ Attribute-based mapping - Simple declarative mapping with attributes
  • Flexible column selection - By name, index, regex pattern, or custom predicate
  • ️ Robust error handling - Optional properties, default values, and custom fallbacks
  • High performance - Streaming API with lazy evaluation and caching
  • Rich type support - Primitives, enums, DateTime, collections, nested objects, and more

Quick Start

csharp
using ExcelMapper;

// Define your model
public class Employee
{
    public string Name { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
}

// Read Excel data
using var importer = new ExcelImporter("employees.xlsx");
var sheet = importer.ReadSheet();
var employees = sheet.ReadRows().ToArray();

That's it! ExcelMapper automatically maps columns to properties by name.

Table of Contents

  • Installation
  • Basic Usage
  • Reading Workbooks
  • Reading Sheets
  • Reading Rows
  • Mapping Strategies
    • Automatic Mapping
    • Attribute-Based Mapping
    • Fluent API Mapping
  • Error Handling
  • Advanced Features
    • Value Mapping
    • Enums
    • Collections and Arrays
    • Dictionaries
    • Nested Objects
    • Custom Converters
    • Custom Transformers and Mappers
  • Special Scenarios
    • Sheets Without Headers
    • Headers Not in First Row
    • Restricting Data Range
  • Error Handling
  • Performance Tips
  • Thread Safety
  • Supported Types
  • CSV Support
  • Common Issues & Troubleshooting
  • Best Practices
  • API Reference
  • Contributing
  • License

Installation

bash
dotnet add package ExcelDataReader.Mapping

Basic Usage

Simple Example

Name Department Salary
Alice Johnson Engineering 95000
Bob Smith Marketing 78000
csharp
using ExcelMapper;

public class Employee
{
    public string Name { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
}

using var importer = new ExcelImporter("employees.xlsx");
var sheet = importer.ReadSheet();
var employees = sheet.ReadRows().ToArray();

Console.WriteLine(employees[0].Name);      // Alice Johnson
Console.WriteLine(employees[1].Salary);    // 78000

Reading Workbooks

Create an ExcelImporter to read Excel or CSV files:

csharp
// From file path
using var importer = new ExcelImporter("data.xlsx");

// From stream
using var stream = File.OpenRead("data.xlsx");
using var importer = new ExcelImporter(stream);

// CSV file
using var importer = new ExcelImporter("data.csv", ExcelImporterFileType.Csv);

// From existing IExcelDataReader (for advanced scenarios)
using var reader = ExcelReaderFactory.CreateReader(stream);
using var importer = new ExcelImporter(reader);

Advanced: Access the underlying ExcelDataReader

csharp
using var importer = new ExcelImporter("data.xlsx");

// Access the underlying reader for advanced scenarios
IExcelDataReader reader = importer.Reader;

// Check number of sheets
int sheetCount = importer.NumberOfSheets;

Reading Sheets

Read All Sheets

csharp
foreach (var sheet in importer.ReadSheets())
{
    Console.WriteLine($"Sheet: {sheet.Name}");
    Console.WriteLine($"Visibility: {sheet.Visibility}");  // Visible, Hidden, or VeryHidden
    Console.WriteLine($"Index: {sheet.Index}");
    Console.WriteLine($"Columns: {sheet.NumberOfColumns}");
}

Sheet Visibility:

  • ExcelSheetVisibility.Visible - Normal visible sheets
  • ExcelSheetVisibility.Hidden - Hidden sheets (can be unhidden in Excel)
  • ExcelSheetVisibility.VeryHidden - Very hidden sheets (requires VBA to unhide)

Read Sheets Sequentially

csharp
// Throws if no more sheets
var sheet1 = importer.ReadSheet();

// Returns false if no more sheets
if (importer.TryReadSheet(out var sheet2))
{
    // Process sheet2
}

Read Sheet by Name

csharp
// Throws if sheet doesn't exist
var sheet = importer.ReadSheet("Sales Data");

// Returns false if sheet doesn't exist
if (importer.TryReadSheet("Sales Data", out var salesSheet))
{
    // Process sheet
}

Read Sheet by Index

csharp
// Throws if index is invalid
var sheet = importer.ReadSheet(0);  // First sheet

// Returns false if index is invalid
if (importer.TryReadSheet(1, out var secondSheet))
{
    // Process sheet
}

Reading Rows

Read All Rows

csharp
// Lazy evaluation - rows are read as you iterate
var rows = sheet.ReadRows();

// Or materialize to array
var employees = sheet.ReadRows().ToArray();

Read Specific Range

csharp
// Read 10 rows starting from row index 5 (after header at index 0)
// Note: startIndex is relative to the beginning of the file, not after the header
var rows = sheet.ReadRows(startIndex: 5, count: 10);

// Example: If header is at row 0, data starts at row 1
// startIndex: 1 = first data row
// startIndex: 11 = 11th data row

Important Notes:

  • startIndex is the zero-based row index from the start of the sheet
  • The startIndex must be after the header row
  • If HeadingIndex is 0 (default), startIndex must be at least 1
  • The method will throw ExcelMappingException if rows don't exist

Read Rows Sequentially

csharp
// Throws if no more rows
var row1 = sheet.ReadRow();

// Returns false if no more rows
if (sheet.TryReadRow(out var row2))
{
    // Process row2
}

Skip Blank Lines

csharp
// Enable blank line skipping (off by default for performance)
importer.Configuration.SkipBlankLines = true;

var rows = sheet.ReadRows();

Security: Column Count Limits

To protect against denial-of-service attacks from malicious Excel files with excessive columns, ExcelMapper enforces a maximum column limit per sheet:

csharp
using var importer = new ExcelImporter("data.xlsx");

// Default limit is 10,000 columns (sufficient for most use cases)
Console.WriteLine(importer.Configuration.MaxColumnsPerSheet);  // 10000

// Adjust the limit if needed for legitimate large files
importer.Configuration.MaxColumnsPerSheet = 20000;

// Or disable the limit entirely (not recommended for untrusted files)
importer.Configuration.MaxColumnsPerSheet = int.MaxValue;

Note: Excel .xlsx files support up to 16,384 columns (XFD). If a sheet exceeds MaxColumnsPerSheet, an ExcelMappingException is thrown with a clear error message.

Security Best Practices:

  • Keep the default limit (10,000) for untrusted/user-uploaded files
  • Only increase the limit when you control the file source
  • Files exceeding the limit will fail immediately before allocating excessive memory

Mapping Strategies

ExcelMapper supports three approaches to mapping Excel rows to objects.

Automatic Mapping

ExcelMapper automatically maps public properties and fields by matching column names. Column name matching is case-insensitive by default using StringComparison.OrdinalIgnoreCase.

Important:

  • Only public instance properties with setters are auto-mapped
  • Only public instance fields are auto-mapped
  • Static members, read-only properties, and indexers are ignored
  • Use [ExcelIgnore] to exclude specific properties/fields Example:
Name Department Position HireDate Salary Active
Alice Johnson Engineering Senior Engineer 2020-03-15 95000 true
Bob Smith Marketing Manager 2019-07-22 78000 true
csharp
public class Employee
{
    public string Name { get; set; }
    public string Department { get; set; }
    public string Position { get; set; }
    public DateTime HireDate { get; set; }
    public decimal Salary { get; set; }
    public bool Active { get; set; }
}

using var importer = new ExcelImporter("employees.xlsx");
var sheet = importer.ReadSheet();
var employees = sheet.ReadRows().ToArray();

Console.WriteLine(employees[0].Name);       // Alice Johnson
Console.WriteLine(employees[0].Position);   // Senior Engineer
Console.WriteLine(employees[1].Salary);     // 78000

Attribute-Based Mapping

Use attributes to declaratively configure mapping behavior. Column name matching is case-insensitive by default (StringComparison.OrdinalIgnoreCase).

Column Name Mapping

Map properties to columns with different names:

Full Name #Age
Alice Johnson 32
Bob Smith 45
csharp
public class Employee
{
    [ExcelColumnName("Full Name")]
    public string Name { get; set; }

    [ExcelColumnName("#Age")]
    public int Age { get; set; }
}

var employees = sheet.ReadRows().ToArray();
Console.WriteLine(employees[0].Name);  // Alice Johnson
Console.WriteLine(employees[1].Age);   // 45

String Comparison Options:

Control how column names are matched using StringComparison:

csharp
public class Employee
{
    // Case-insensitive matching (default)
    [ExcelColumnName("Full Name")]
    public string Name { get; set; }

    // Case-sensitive matching
    [ExcelColumnName("Department", StringComparison.Ordinal)]
    public string Department { get; set; }

    // Culture-aware case-insensitive matching
    [ExcelColumnName("Città", StringComparison.CurrentCultureIgnoreCase)]
    public string City { get; set; }
}

Available StringComparison Options:

  • StringComparison.OrdinalIgnoreCase (default) - Case-insensitive, culture-invariant
  • StringComparison.Ordinal - Case-sensitive, culture-invariant
  • StringComparison.CurrentCultureIgnoreCase - Case-insensitive using current culture
  • StringComparison.CurrentCulture - Case-sensitive using current culture
  • StringComparison.InvariantCultureIgnoreCase - Case-insensitive using invariant culture
  • StringComparison.InvariantCulture - Case-sensitive using invariant culture

Multiple Column Name Variants

Try multiple column names in order of preference:

csharp
public class Employee
{
    public string Name { get; set; }

    // Try these column names in order (case-insensitive by default)
    [ExcelColumnNames("Age", "#Age", "Years")]
    public int Age { get; set; }

    // Or use multiple attributes with different comparison modes
    [ExcelColumnName("Dept", StringComparison.OrdinalIgnoreCase)]
    [ExcelColumnName("Department", StringComparison.Ordinal)]
    public string Department { get; set; }
}

Pattern Matching

Match columns using regex patterns or custom matchers:

csharp
public class Employee
{
    public string Name { get;

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

C#csvexcelxlsx

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言