流畅地将 Excel 行映射到 C# 对象
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.
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.
dotnet add package ExcelDataReader.Mapping| Name | Department | Salary |
|---|---|---|
| Alice Johnson | Engineering | 95000 |
| Bob Smith | Marketing | 78000 |
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); // 78000Create an ExcelImporter to read Excel or CSV files:
// 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
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;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 sheetsExcelSheetVisibility.Hidden - Hidden sheets (can be unhidden in Excel)ExcelSheetVisibility.VeryHidden - Very hidden sheets (requires VBA to unhide)// Throws if no more sheets
var sheet1 = importer.ReadSheet();
// Returns false if no more sheets
if (importer.TryReadSheet(out var sheet2))
{
// Process sheet2
}// 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
}// 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
}// Lazy evaluation - rows are read as you iterate
var rows = sheet.ReadRows();
// Or materialize to array
var employees = sheet.ReadRows().ToArray();// 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 rowImportant Notes:
startIndex is the zero-based row index from the start of the sheetstartIndex must be after the header rowHeadingIndex is 0 (default), startIndex must be at least 1ExcelMappingException if rows don't exist// Throws if no more rows
var row1 = sheet.ReadRow();
// Returns false if no more rows
if (sheet.TryReadRow(out var row2))
{
// Process row2
}// Enable blank line skipping (off by default for performance)
importer.Configuration.SkipBlankLines = true;
var rows = sheet.ReadRows();To protect against denial-of-service attacks from malicious Excel files with excessive columns, ExcelMapper enforces a maximum column limit per sheet:
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:
ExcelMapper supports three approaches to mapping Excel rows to objects.
ExcelMapper automatically maps public properties and fields by matching column names. Column name matching is case-insensitive by default using StringComparison.OrdinalIgnoreCase.
Important:
[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 |
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); // 78000Use attributes to declaratively configure mapping behavior. Column name matching is case-insensitive by default (StringComparison.OrdinalIgnoreCase).
Map properties to columns with different names:
| Full Name | #Age |
|---|---|
| Alice Johnson | 32 |
| Bob Smith | 45 |
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); // 45String Comparison Options:
Control how column names are matched using StringComparison:
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-invariantStringComparison.Ordinal - Case-sensitive, culture-invariantStringComparison.CurrentCultureIgnoreCase - Case-insensitive using current cultureStringComparison.CurrentCulture - Case-sensitive using current cultureStringComparison.InvariantCultureIgnoreCase - Case-insensitive using invariant cultureStringComparison.InvariantCulture - Case-sensitive using invariant cultureTry multiple column names in order of preference:
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; }
}Match columns using regex patterns or custom matchers:
public class Employee
{
public string Name { get;暂无开放 Issues,或尚未同步最近议题。