如何在 c# 中使用 excel 数据 reader 获取特定单元格的内容?

How to get the contents a particular cell using excel data reader in c#?

我有一个类似的 xlsx 文件(这是第一个 sheet)

Postcode    Sales_Rep_ID    Sales_Rep_Name  Year    Value
2121            456             Jane        2011    ,219
2092            789             Ashish      2012    ,322
2128            456             Janet       2013    ,879
2073            123             John        2011    ,491

如何获取名为 Year 的列的特定值,其值 Sales_Rep_Name 是 Janet?我被困在下面的代码中,不知道该怎么做?

FileStream stream = File.Open(@"C:\Users\Bumba\Downloads\Sample-Sales-Data.xlsx", FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

DataSet result = excelReader.AsDataSet(new ExcelDataSetConfiguration() {
ConfigureDataTable = (_) => new ExcelDataTableConfiguration() {
    UseHeaderRow = true
}
});

foreach (DataTable element in result.Tables) {
    Console.WriteLine(element.Columns["Year"].ToString());
    //what to do??????
}

excelReader.Close();
Console.ReadLine();

有人帮忙....

最简单的选择是枚举 table (sheet) 行并将 Sales_Rep_Name 列中的值与所需值 ("Janet") 进行比较:

foreach (DataTable table in result.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        var salesRepName = (string)row["Sales_Rep_Name"];
        if (String.Equals(salesRepName, "Janet"))
        {
            var year = (int)(double)row["Year"];
            Console.WriteLine($"Janet's year is {year}");
        }
    }
}

您也可以使用 DataTable.Select(string filterExpression) 方法来匹配所需的行:

foreach (DataTable table in result.Tables)
{
    foreach (DataRow row in table.Select("Sales_Rep_Name = 'Janet'"))
    {
        var year = (int)(double)row["Year"];
        Console.WriteLine($"Janet's year is {year}");
    }
}

第二个选择会更快(当数据很大时),但是第一个更灵活并且允许使用更复杂的过滤器。

//Code to get an specific cell value
var asOfCell = "AB2";
var match = Regex.Match( asOfCell, @"(?<col>[A-Z]+)(?<row>\d+)" );
var colStr = match.Groups["col"].ToString();
//I rest 1 for colunm and row due to I will work with an array and it begins by zero.
var col = (int) ( colStr.Select( ( t, i ) => ( colStr[i] - 64 ) * Math.Pow( 26, colStr.Length - i - 1 ) ).Sum() ) - 1;
var rowSelected = int.Parse( match.Groups["row"].ToString() ) - 1;
var cellSelectedValue = table.Rows[rowSelected][col];