c# - 从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;
}
解决方案
您想循环值直到找到匹配项。您的循环现在说“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());
或类似的东西。
推荐阅读
- aws-sdk-js - JS AWS S3 SDK getSignedURL 不返回任何内容
- stripe-payments - Stripe 进行付款错误 500(内部服务器错误)
- c++ - Eigen 稀疏矩阵 innerIndexPtr() 和 outerIndexPtr() 返回类型转换错误?
- c++ - 使用重复这个关键字?
- reactjs - React-Leaflet:平移地图时标记消失
- junit5 - 在 JUnit5 中创建的 @TempDir 具有空值
- python - Pandas - re-arrange columns by ascending order
- php - 数据库中的多项选择,无需
- c - CopyFileEx 后如何刷新缓冲数据?
- excel - 如果 C 列中的单元格,则 VBA 代码替换 D 列中的值