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

时间:2018-02-11 14:00:37

标签: c# excel exceldatareader

我有一个xlsx文件(它是第一张)

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

如何获取名为的列的特定值,其 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();

有人帮助......

2 个答案:

答案 0 :(得分:3)

最简单的选择就是枚举表(表)行并将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}");
    }
}

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

答案 1 :(得分:0)

//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];