首页 > 解决方案 > 从excel文件读取时for循环仅返回第一个值

问题描述

我正在尝试输入一个单元格值并从 .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;
}

标签: c#

解决方案


您想循环值直到找到匹配项。您的循环现在说“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()); 

或类似的东西。


推荐阅读