Column mapping and conversion
On this page
Define a stable contract
ExcelColumnAttribute belongs to TExcel and applies to public properties. Typed reads also require assignable properties and a public parameterless constructor.
Install TExcel using the quick start, put this program in Program.cs, and run dotnet run. It creates report.xlsx and reads the same model back to check the export contract.
using System.Globalization;
using TExcel;
Excel.SaveAs("report.xlsx", new[]
{
new ReportRow
{
Code = "0007",
OccurredAt = new DateTime(2026, 1, 2, 3, 4, 5),
InternalToken = "not-exported"
}
});
var saved = Excel.Query<ReportRow>("report.xlsx").Single();
Console.WriteLine($"Code: {saved.Code}");
Console.WriteLine($"Occurred at: {saved.OccurredAt.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)}");
Console.WriteLine($"Internal token restored: {saved.InternalToken.Length != 0}");
Console.WriteLine($"Headers: {string.Join(", ", Excel.QueryAsDictionary("report.xlsx").First().Keys)}");
/// <summary>报告行只公开业务字段。</summary>
public sealed class ReportRow
{
/// <summary>业务标识保持为文本。</summary>
[ExcelColumn("Code", Order = 0)]
public string Code { get; set; } = "";
/// <summary>按约定格式输出事件时间。</summary>
[ExcelColumn("Occurred at", Order = 1, Format = "yyyy-MM-dd HH:mm:ss")]
public DateTime OccurredAt { get; set; }
/// <summary>内部凭据不参与读写。</summary>
[ExcelColumn(Ignore = true)]
public string InternalToken { get; set; } = "";
}Expected output:
Code: 0007
Occurred at: 2026-01-02 03:04:05
Internal token restored: False
Headers: Code, Occurred atInternalToken is excluded and retains its model initializer when read back. Running again overwrites the example file.
| Setting | Contract |
|---|---|
Name / constructor argument | Header; defaults to the property name |
Order | Nonnegative values specify order; default -1 is unspecified |
Ignore | Exclude a property |
Format | Format written values, such as date text |
Assign Order to every column for a fixed export order. Reads with headers bind by property name or custom header without case sensitivity, regardless of input column order. Unknown headers do not automatically produce business validation errors.
Format formats values. Date reads try that format first but also have other conversion paths, so it does not enforce one exclusive input format. Worksheet NumberFormat controls display formatting; see worksheet design.
Conversion errors
onConvertError receives the failed cell’s text and exception. This second program runs independently: it creates input with a valid quantity and an invalid quantity, collects conversion failures, and rejects persistence.
using TExcel;
IDictionary<string, object?>[] input =
[
new Dictionary<string, object?> { ["Code"] = "0007", ["Quantity"] = "12" },
new Dictionary<string, object?> { ["Code"] = "0008", ["Quantity"] = "bad" }
];
Excel.SaveAs("conversion-input.xlsx", input);
var failures = new List<string>();
var rows = Excel.Query<StockRow>("conversion-input.xlsx", onConvertError: RecordFailure).ToList();
foreach (var row in rows)
{
Console.WriteLine($"{row.Code}: {row.Quantity}");
}
Console.WriteLine($"Conversion errors: {failures.Count}");
if (failures.Count != 0)
{
Console.WriteLine("Import rejected; nothing was saved.");
return;
}
/// <summary>保留失败单元格的文本,供保存前统一判断;异常可另作诊断。</summary>
void RecordFailure(string value, Exception error) => failures.Add(value);
/// <summary>类型转换只负责得到字段值,不代替库存业务校验。</summary>
public sealed class StockRow
{
/// <summary>业务编码即使全为数字也按文本读取。</summary>
public string Code { get; set; } = "";
/// <summary>无初始值时,非法输入转换失败后仍可能保留零值。</summary>
public int Quantity { get; set; }
}Expected output:
0007: 12
0008: 0
Conversion errors: 1
Import rejected; nothing was saved.When the callback returns normally or is absent, reading continues with the failed conversion’s default value; the invalid quantity here becomes 0. Throwing from the callback stops reading.
Empty strings may produce defaults or null references without conversion errors. Applications still validate required values, ranges, uniqueness, name relationships and permissions. The callback supplies neither row numbers nor column names. Use raw rows and the complete import example for precise locations, duplicate-header checks or strict date syntax.
Identity and precision
Use string for codes with leading zeroes and identifiers beyond Excel’s numeric precision. Display formatting cannot recover a rounded identifier. Where raw text, notation or formulas matter, inspect ExcelCell.Type, RawValue and HasFormula.