如何在C#中动态读取Excel数据并映射到列表
动态读取列位置不固定的Excel数据并映射字段
核心思路是先建立表头列名与列索引的映射关系,之后通过列名动态查找对应索引来读取单元格数据,不再依赖固定的列位置。
实现步骤
- 第一步:遍历Excel的表头行(第一行),创建列名到列索引的字典映射
- 第二步:遍历数据行时,通过字典根据列名获取对应索引,再读取单元格值
- 可选:处理列名大小写不敏感、缺失列的异常情况
修改后的代码示例
DataSet dataSet = excelStream(files); DataTable tbl = dataSet.Tables[0]; // 建立列名与索引的映射字典(支持大小写不敏感) Dictionary<string, int> columnIndexMap = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); for (int col = 0; col < tbl.Columns.Count; col++) { string columnName = tbl.Rows[0][col].ToString().Trim(); // 去除列名前后空格 columnIndexMap[columnName] = col; } List<Model> Listmodel = new List<Model>(); // 从第二行开始遍历数据行 for (int i = 1; i < tbl.Rows.Count; i++) { DataRow row = tbl.Rows[i]; Model model = new Model(); // 通过列名动态获取索引,读取数据 if (columnIndexMap.TryGetValue("OrgName", out int orgNameIndex)) model.OrgName = row[orgNameIndex].ToString(); if (columnIndexMap.TryGetValue("OrgNumber", out int orgNumberIndex)) model.OrgNumber = row[orgNumberIndex].ToString(); if (columnIndexMap.TryGetValue("OrgLevel", out int orgLevelIndex)) model.OrgLevel = row[orgLevelIndex].ToString(); if (columnIndexMap.TryGetValue("OrgState", out int orgStateIndex)) model.OrgState = row[orgStateIndex].ToString(); if (columnIndexMap.TryGetValue("OrgText", out int orgTextIndex)) model.OrgText = row[orgTextIndex].ToString(); if (columnIndexMap.TryGetValue("OrgCode", out int orgCodeIndex)) model.OrgCode = row[orgCodeIndex].ToString(); if (columnIndexMap.TryGetValue("OrgStatus", out int orgStatusIndex)) model.OrgStatus = row[orgStatusIndex].ToString(); Listmodel.Add(model); }
额外优化点
- 大小写不敏感:字典初始化时使用
StringComparer.OrdinalIgnoreCase,避免用户上传的列名大小写不一致导致匹配失败 - 缺失列处理:使用
TryGetValue而不是直接索引字典,避免因缺失列抛出异常,可根据业务需求添加日志提示或默认值赋值 - 列名去空格:读取列名时调用
Trim(),处理用户表头列名前后有空格的情况
内容的提问来源于stack exchange,提问作者Venkat457
相关产品推荐
相关产品推荐

