Getting the length of a row in excel

178 views Asked by At

I want to put some rows of excel in a list in c#. At the moment I use this:

private static Microsoft.Office.Interop.Excel.ApplicationClass appExcel;
private static Workbook newWorkbook = null;
private static _Worksheet objsheet = null;

for (int j = 1; j < 3000; j++)
{
  list.add(excel_getValue("A"+j)); //ROW A in excel
}

My excel row(A) is ~2800 long and there can be stuff added, that's why I made it 3000 just to be sure. But is there a way to get the exact number of filled colomns in a specific row? Something like:

objsheet.get_Range("A").EntireRow.Height(); //this doesn't work
2

There are 2 answers

3
Gino On BEST ANSWER

That's clever but i wouldn't do that since the user can actually get to modify that number. I would rather cicle the row until the cell is empty and i'd consider that cell the end of my cicle

bool endReach=false;    
for (int j = 1; !endReach; j++)
    {
      if(excel_getValue("A"+j) == "" && excel_getValue("A"+(j+1)) == "")
      {
             endReach=true;
       }else{
             list.add(excel_getValue("A"+j)); //ROW A in excel
       }
    }

Be careful because if the user fills all the rows it may throw an exception. PS: I'm not very sure about the "value" property of the cell so you may have to change that.
Hope it helps!

1
wouter On

Cannot find a clear solution, so will do the following to fix it:

In Excel I leave the first column of the first row empty with a sum in it: it just sums up all the data in the cells under it, if its full it will count +1 else +0, and I'm gonna read that number in C#. :)

With this formula in Excel:

=COUNTA(A2:A5000)