Harvey Lin Harvey Lin - 16 days ago 4
C# Question

Iterate all rows of a specific column number in excel sheet and do some processing on each row value

I am trying to make a loop that goes though all rows of a specific column number in an excel sheet, say column number 16, and do some processing on the values of each cell in each row.
For example, the loop will iterate though cells 1,16, then next one goes to cell 2,16, then next one 3,16....then goes all the way to however many rows that sheet has in that specific column number, in this case, column number 16.
So far I am able to get and set the value of a single excel cell using statements such as this:

string cellValue = excelSheet.Cells[1, 16].Value.ToString();
//Do some processing.
excelSheet.Cells[1, 16] = cellValue;


But I want to loop though the row number to the tone of something like this inside my loop:

string cellValue = excelSheet.Cells[n, 16].Value.ToString();
//Do some processing.
excelSheet.Cells[n, 16] = cellValue;


Any thoughts?

Answer

You need a for loop here:

for(int n = 1; n <= excelSheet.Columns.Count; n++)
{
    string cellValue = excelSheet.Cells[n, 16].Value.ToString();
    //Do some processing.
    excelSheet.Cells[n, 16] = cellValue; 
}