使用 exceldatareader 库读取 excel 文件,通过反射将每一行的数据映射到 c# 对象。具体做法是:定义一个包含属性与列名匹配的实体类,调用 asdataset() 获取数据表,遍历 datatable.rows 并使用 setvalue 填充对象。若遇到列名不匹配的情况,需确保实体属性名与 excel 表头完全一致,否则对应字段将为默认值。

如何根据 Excel 表头自动填充对象属性?
利用 System.Reflection 中的 PropertyInfo 和 SetValue 方法实现自动映射。在代码中,先获取实体类型的属性列表,然后遍历 Excel 的每一行,查找与属性名相同的列索引,找到后赋值。这样无需手动编写每列的转换逻辑,即可处理任意结构的表格数据。

using System;
using System.Data;
using System.IO;
using System.Reflection;
using ExcelDataReader;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
// 假设已创建 test.xlsx,第一行为 Name, Age
using (var stream = File.Open("test.xlsx", FileMode.Open, FileAccess.Read))
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var result = reader.AsDataSet();
DataTable table = result.Tables[0];
foreach (DataRow row in table.Rows)
{
Person p = new Person();
Type type = typeof(Person);
for (int i = 0; i < table.Columns.Count; i++)
{
string colName = table.Columns[i].ColumnName;
PropertyInfo prop = type.GetProperty(colName);
if (prop != null && row[i] != DBNull.Value)
{
prop.SetValue(p, Convert.ChangeType(row[i], prop.PropertyType));
}
}
Console.WriteLine($"{p.Name}, {p.Age}");
}
}
}
}
运行上述代码,控制台将输出 Excel 中每一行对应的 Name 和 Age 值。如果某列在实体类中不存在,该列数据会被忽略;如果实体属性存在但 Excel 列为空,则保持默认值。
如何处理 Excel 中的日期类型映射?
当 Excel 单元格包含日期时,ExcelDataReader 默认返回 DateTime 或 double 类型(取决于格式)。在映射过程中,需特别注意类型转换。如果实体属性是 DateTime,直接赋值即可;如果是字符串,需显式转换。此外,若 Excel 单元格为空,row[i] 为 DBNull.Value,必须跳过以避免异常。
using System;
using System.Data;
using System.IO;
using System.Reflection;
using ExcelDataReader;
public class EventRecord
{
public string Title { get; set; }
public DateTime Date { get; set; }
}
class Program
{
static void Main()
{
using (var stream = File.Open("events.xlsx", FileMode.Open, FileAccess.Read))
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var result = reader.AsDataSet();
DataTable table = result.Tables[0];
foreach (DataRow row in table.Rows)
{
EventRecord rec = new EventRecord();
Type type = typeof(EventRecord);
for (int i = 0; i < table.Columns.Count; i++)
{
string colName = table.Columns[i].ColumnName;
PropertyInfo prop = type.GetProperty(colName);
if (prop != null && row[i] != DBNull.Value)
{
object value = row[i];
if (prop.PropertyType == typeof(DateTime) && value is double d)
{
value = DateTime.FromOADate(d);
}
prop.SetValue(rec, Convert.ChangeType(value, prop.PropertyType));
}
}
Console.WriteLine($"{rec.Title} on {rec.Date:yyyy-MM-dd}");
}
}
}
}
此段代码展示了如何处理日期列。如果 Excel 中的日期是以序列号形式存储的(如 44562.0),代码会将其转换为标准的 DateTime 对象。若单元格为空,程序不会抛出异常,而是跳过该属性的设置,保持 EventRecord 中 Date 的默认值(即 DateTime.MinValue)。
当 Excel 列名与属性名不一致时怎么办?
如果 Excel 表头是 User_Name 而实体属性是 Name,直接映射会失败。此时需要在代码中添加一个映射字典,或者在遍历时进行名称修正。例如,可以定义一个静态字典 ColumnMapping,将 Excel 列名映射到实体属性名。在循环中,先检查当前列名是否在字典中,如果在,则使用映射后的属性名进行赋值。这种方法提高了代码的灵活性,允许 Excel 结构变化而不必修改实体类。
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using ExcelDataReader;
public class User
{
public string Name { get; set; }
public string Email { get; set; }
}
class Program
{
private static readonly Dictionary<string, string> ColumnMapping = new Dictionary<string, string>
{
{ "User_Name", "Name" },
{ "Email_Address", "Email" }
};
static void Main()
{
using (var stream = File.Open("users.xlsx", FileMode.Open, FileAccess.Read))
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var result = reader.AsDataSet();
DataTable table = result.Tables[0];
foreach (DataRow row in table.Rows)
{
User u = new User();
Type type = typeof(User);
for (int i = 0; i < table.Columns.Count; i++)
{
string colName = table.Columns[i].ColumnName;
string propName = ColumnMapping.ContainsKey(colName) ? ColumnMapping[colName] : colName;
PropertyInfo prop = type.GetProperty(propName);
if (prop != null && row[i] != DBNull.Value)
{
prop.SetValue(u, Convert.ChangeType(row[i], prop.PropertyType));
}
}
Console.WriteLine($"{u.Name}: {u.Email}");
}
}
}
}
通过引入映射字典,即使 Excel 列名发生变化,只要更新字典即可适配。这种方案避免了硬编码列索引,使得代码更易于维护。同时,它确保了只有匹配的列才会被赋值,未匹配的列将被忽略,从而防止错误的数据进入对象。


















