简体   繁体   中英

C# iterate over a row in Excel

I need to iterate over a specific excel row. For now I've got a code to iterate over a column and I want it to be similar to that. It looks like this:

int columnLength = xlWorkSheet.UsedRange.Rows.Count;
string lastCell = Regex.Replace(CONST_FIRST_CELL, @"\d+", columnLength.ToString()); //will give me the last cell in the column
var excelColumn = xlWorkSheet.Range[CONST_FIRST_CELL, lastCell ];
    if (excelColumn == null)
    {
      throw new Exception("bad col");
    }
    for (int i = 1; i < columnLength ; i++)
    {
      Excel.Range currentValue = excelColumn [i];
      ....DO SOME STUFF....
    }

how can I iterate over a specific row? I'm not sure how to get the last column like I got the last row cell in the above implementation since then I just had to switch a number with the length but now I somehow need to get the correct last cell of a row (which means switching the letters somehow ie C4 to AD4) in order to get the range of first cell row and last...

The best solution I guess involves a foreach loop somehow?

You were almost there, your loop just needs some tuning:

  //Input all the Int values you want
  int targetRow = 1; 
  int startCol = 1;
  int maxCol = 10; //With this value the loop below will iterate until column 9 (inclusive)
  for (int i = startCol; i < maxCol ; i++)
  {
      Excel.Range currentRange = (Excel.Range)xlWorkSheet.Cells[targetRow, i];
      if (currentRange.Value2 != null)
      {
          string curVal = currentRange.Value2.ToString();
      }
  }

IMO this is the best way to iterate through cells (by considering rows and/or columns). You can do it differently (on the lines of what you were trying): iterating within the columns of a given range (you would need to define the range as Excel.Range Type and then rely on the in-built property Columns ), although I think that this can be more confusing. Example: if you have as input range C1:H5, "C:C" is the first column, "D:D" the second column, etc. With my approach, the first column will always be "A:A", the second column "B:B", etc.

Example of iterating through columns in a given range ( inputRange ):

foreach(Excel.Range curCol in inputRange.Columns)
{
    if (curCol.Value2 != null) 
    {
       //As far as each column only has one row, each column can be associated with a cell
        string curVal = curCol.Value2.ToString();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM