快速开始
本页目录
使用 .NET 10 控制台项目写出三列、两条记录的 XLSX,再按相同列映射读回,无需安装 Microsoft Excel。
创建项目
dotnet new console -n ExcelDemo -f net10.0
cd ExcelDemo
dotnet add package TExcel写入并读取
将下面内容放入 Program.cs。顶层语句位于类型定义之前,执行后在当前目录生成 devices.xlsx 并输出设备名。
using TExcel;
var devices = new[]
{
new DeviceRow { Code = "P-001", Name = "进水泵", Enabled = true },
new DeviceRow { Code = "P-002", Name = "出水泵", Enabled = false }
};
Excel.SaveAs("devices.xlsx", devices, sheetName: "Devices");
foreach (var device in Excel.Query<DeviceRow>("devices.xlsx", sheetName: "Devices"))
{
Console.WriteLine($"{device.Code}: {device.Name}");
}
/// <summary>设备工作表的导入导出模型。</summary>
public sealed class DeviceRow
{
/// <summary>用文本保留设备编码及其前导零。</summary>
[ExcelColumn("设备编码", Order = 0)]
public string Code { get; set; } = "";
/// <summary>面向业务识别的设备名称。</summary>
[ExcelColumn("设备名称", Order = 1)]
public string Name { get; set; } = "";
/// <summary>设备是否参与当前配置。</summary>
[ExcelColumn("启用", Order = 2)]
public bool Enabled { get; set; }
}dotnet run预期输出:
P-001: 进水泵
P-002: 出水泵在运行目录打开 devices.xlsx,Devices 工作表的表头依次为“设备编码、设备名称、启用”,下面是两条设备记录。再次运行会重新创建同名文件;需要保留历史导出时为每次导出选择不同路径。
Query<T> 延迟枚举。读取和文件访问会在遍历时发生;使用 ToList() 会把结果完整加载到内存。
查看工作表
var sheets = Excel.GetSheets("devices.xlsx");
foreach (var sheet in sheets)
{
Console.WriteLine($"{sheet.Index}: {sheet.Name}");
}上面的工作表枚举片段放在 Program.cs 的类型声明之前执行。sheetName 不传时读取第一个工作表;导入外部模板时建议显式指定名称,避免工作表顺序改变后读错数据。
下一步怎么选
若文件打不开,先确认写入已完成、文件未被其他进程占用;若读回字段为空,核对实际表头与 ExcelColumn 名称。业务必填、重复编码和数据库约束应在导入预检阶段检查。