从Excel文件读取时for循环仅返回第一个值

时间:2018-09-05 14:26:59

标签: c#

我试图输入一个单元格值并显示.xlsx文件中的相应单元格值。它仅给出第一个单元格值的结果,而不循环。有人可以帮忙吗?我的Excel文件有两列和许多行。我正在输入通过控制台的值,该值等于第一列中的任何值,然后它应该显示第二列值。如果我输入第一个单元格值,则给出输出,但是如果我在第一列中输入任何其他值,则不给出结果

for (int i = 1, j = 1; excelSheet.Cells[i, 1].value.ToString() == a.ToString(); i++, j++)
{
    string b = excelSheet.Cells[j, 2].value.ToString();
    Console.WriteLine(b);
    Console.ReadLine();

    if (excelSheet.Cells[i, 1].value == null)
        break;
}

1 个答案:

答案 0 :(得分:1)

要在找到匹配项之前循环值。您的循环现在会说“ Loop while Column1 = a”,这当然会在第一次尝试后退出,因为该行的Column1中的值不等于a

//Start at column 1; Exit the loop if you hit a null
for (int i = 1; excelSheet.Cells[i, 1].value.ToString() != null; i++)
{
    //test for a match
    if (excelSheet.Cells[i, 1].value.ToString() = a.ToString()){

        //capture the match to a variable; write it to console; read from console for some reason
        string b = excelSheet.Cells[i, 2].value.ToString();
        Console.WriteLine(b);
        Console.ReadLine();

        //include this if you want to exit after the first match
        //exclude if you want the last match
        break;
    }  
}

我不确定100%在这里使用的是什么库,但是您也可以执行以下操作:

Console.WriteLine(excelSheet.Range["A1", "B900000"].Find(a.ToString()).Offset[0, 1].value.ToString()); 

或者类似的东西。