Reading entities, dictionaries and raw rows
On this page
Choose a model
| Result | Use case |
|---|---|
IEnumerable<T> / IAsyncEnumerable<T> | Known columns and types; T needs a public parameterless constructor |
IDictionary<string, string?> | Dynamic headers and previews; values remain text |
object?[] | Positional processing without a dictionary per row |
ExcelRow | Original worksheet row numbers and optional cell facts |
Typed reads bind headers once and project the current row directly, avoiding an intermediate dictionary per row. Arrays avoid a header hash table but still allocate an owned array for each row. Enable includeCellFacts when original cell facts are required. See performance and large files for model costs and 100,000-row comparisons.
Complete example: four views of the same workbook
Install TExcel using the quick start, put this program in Program.cs, and run dotnet run. It creates read-models.xlsx and reads it sequentially. Running again overwrites the file.
using TExcel;
Excel.SaveAs("read-models.xlsx", new[]
{
new DeviceRow { Code = "0001", Name = "Inlet pump" },
new DeviceRow { Code = "0002", Name = "Outlet pump" }
}, sheetName: "Devices");
using var reader = Excel.CreateReader("read-models.xlsx");
foreach (var device in reader.ReadSheet<DeviceRow>("Devices"))
{
Console.WriteLine($"Typed: {device.Code}, {device.Name}");
}
foreach (var row in reader.ReadSheetAsDictionary("Devices"))
{
Console.WriteLine($"Dictionary: {row["Code"]}, {row["Name"]}");
}
foreach (var row in reader.ReadSheetAsArray("Devices"))
{
Console.WriteLine($"Array: {row[0]}, {row[1]}");
}
foreach (var row in reader.ReadSheetRows("Devices", includeCellFacts: true))
{
Console.WriteLine($"Row {row.Number}: {row.Values[0]}, facts: {row.Cells.Length}");
}
/// <summary>固定表头的设备行,业务编码按文本读写。</summary>
public sealed class DeviceRow
{
/// <summary>第一列保留数字编码的前导零。</summary>
[ExcelColumn("Code", Order = 0)]
public string Code { get; set; } = "";
/// <summary>第二列提供设备显示名称。</summary>
[ExcelColumn("Name", Order = 1)]
public string Name { get; set; } = "";
}Expected output:
Typed: 0001, Inlet pump
Typed: 0002, Outlet pump
Dictionary: 0001, Inlet pump
Dictionary: 0002, Outlet pump
Array: 0001, Inlet pump
Array: 0002, Outlet pump
Row 2: 0001, facts: 2
Row 3: 0002, facts: 2Dictionaries and arrays do not infer numbers, dates or Booleans. Use typed models or explicit conversion rules.
Run enumerations sequentially on one reader and finish them within its using scope.
Dictionaries and headers
Excel.QueryAsDictionary(path, sheetName) manages a reader internally. An explicit reader is convenient for processing multiple worksheets sequentially.
hasHeader defaults to true. Set it to false explicitly for headerless files and define columns by position. This independent program generates headerless input and includes its first device:
using TExcel;
Excel.SaveAs("headerless.xlsx", new[]
{
new { Code = "0007", Name = "Pump" },
new { Code = "0008", Name = "Valve" }
}, printHeader: false);
using var reader = Excel.CreateReader("headerless.xlsx");
foreach (var row in reader.ReadSheetAsArray(hasHeader: false))
{
if (row.Length < 2)
throw new InvalidDataException("Expected Code and Name columns.");
Console.WriteLine($"{row[0]}: {row[1]}");
}Expected output:
0007: Pump
0008: ValveHeaderless typed mapping needs an agreed property-to-column contract.
Original row numbers and formulas
ReadSheetRows returns original row numbers and the fields below. includeCellFacts defaults to false; enabling it populates row.Cells:
| Data | Interpretation |
|---|---|
row.Values[index] | Resolved value text at a zero-based position; missing cells may be null |
row.Number | Physical worksheet row number, including the header’s position |
cell.Column / cell.Type | One-based column number and OpenXML type marker |
cell.RawValue | Lexical content, possibly a shared-string index rather than a device code |
cell.HasFormula | Presence of a formula element, without guaranteeing a fresh or correct cached result |
Async enumeration
using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30));
await foreach (var device in Excel.QueryAsync<DeviceRow>(
"read-models.xlsx", "Devices", cancellationToken: cancellation.Token))
{
Console.WriteLine($"Async: {device.Code}");
}Place the fragment before the first program’s type declaration to add Async: 0001 and Async: 0002. Pass cancellation to reading and subsequent processing. See conversion errors.
Consume large files row by row
Enumerate directly, validating each row or writing bounded business batches instead of calling ToList before processing. Enumerating again performs another read; retain a deliberately bounded subset when results must be reused. Limit stored error details and preview rows during strict validation.
Streaming reads still load shared strings, so unique text increases memory. See large-file guidance for costs and batching.
Diagnose unexpected reads
| Symptom | Check |
|---|---|
| First business record missing | Headerless input requires hasHeader: false |
| Requested sheet missing | Inspect Excel.GetSheets; no name selects the first sheet, while an unknown explicit name throws an argument exception |
| Unexpected dictionary keys or entity values | Inspect actual headers; validate required and duplicate columns for fixed templates |
Empty Cells | Confirm includeCellFacts; the default disables collection |
| Gaps in row numbers or absent empty rows | Locate errors with Number; blank gaps do not become business records |
Validate external uploads with archive checks. Use the complete import example for error locations and validation before persistence.