【问题标题】:How should I configure excel column mapping to a class property in C#?我应该如何在 C# 中配置 excel 列映射到类属性?
【发布时间】:2021-11-25 16:52:03
【问题描述】:

我正在从 Excel 文件构建导入。我想将数据存储到我的班级中。 我想避免将列名硬编码到我的代码中,因为用户经常更改它们。我正在考虑一个配置文件,我可以将列名映射到类属性。

<excelFileSetting filePath="path\to\my\file.xlsx"> 
    <columnMappings>
        <add columnName="Excel Col Name" classProperty="MyNamespace.MyClass.MyProperty" />
    </columnMappings>
</excelFileSetting>

我知道如何构建配置部分以及如何读取值。

问题是当我读取 Excel 文件时,如何将单元格值映射到属性? 我将excel文件内容放入数据表中。 现在,我这样做是为了创建我的对象:

var myClass = new MyClass{
    MyProperty = dataRow["Excel Col Name"].ToString() 
}

您对我如何实现映射有任何想法吗? 或者也许我的方向不对,我应该使用另一种方法?

我查看了 nuget LinqToExcel,但我正在使用的 excel 文件格式不正确,我无法更改格式。

【问题讨论】:

  • 如果列名是唯一改变的,那么按列索引映射属性:MyProperty = dataRow[0].ToString()
  • @MetroSmurf 好点。我知道我在想一些太复杂的事情!谢谢。

标签: c# excel


【解决方案1】:

就像@MetroSurf 建议的那样,我使用基于字符串的映射的列索引。 我在想一些太复杂的事情。

这是我在 app.config 中所做的:

<ReportConfig 
    filePath="C:\temp\myFile.xslm"
    sheetToRead="MASTER"
    projectNameColumnNumber="4"
    customerNameColumnNumber="5"
    startDateColumnNumber="18"
    plannedDateColumnNumber="19">
  </ReportConfig>

然后,当我在课堂上分配时,我可以这样做:

var reportRow = new ReportRow{ 
    ProjectName = dataRow[reportConfig.ProjectNameColumnNumber].ToString()
}

有关如何在 app.config 中实现自定义配置部分的详细信息,我建议阅读以下内容:https://ivankahl.com/creating-custom-configuration-sections-in-app-config/

【讨论】:

    猜你喜欢
    • 2023-03-05
    • 1970-01-01
    • 2017-05-18
    • 2012-09-16
    • 1970-01-01
    • 2021-09-27
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多