Reputation: 27
I am trying to enter a cell value and display corresponding cell value from .xlsx file. It is giving result only for 1st cell value, it is not looping. Can anyone help? My excel file has two columns and many rows. I am entering value of a through console which is equal to any value in 1st column then it should display 2nd column value. If i enter 1st cell value it is giving output but if i enter any other value in 1st column it is not giving result
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;
}
Upvotes: 1
Views: 449
Reputation: 50263
You want to loop values UNTIL you find a match. Your loop right now says "Loop while Column1 = a
" which of course will exit after it's first attempt as whatever value is in Column1
for that row is not equal to 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;
}
}
I'm not 100% certain what library is in use here, but you may also be able to do something like:
Console.WriteLine(excelSheet.Range["A1", "B900000"].Find(a.ToString()).Offset[0, 1].value.ToString());
Or something like that.
Upvotes: 1