24

I am looking to programmatically pull data from an Excel worksheet and insert it into a database table.

How do I determine the number of columns and rows in a worksheet or otherwise iterate the rows?

I have

Excel._Worksheet worksheet = (Excel._Worksheet)workbook.ActiveSheet;

I tried worksheet.Range.Rows.Count

which tosses up

Indexed property 'Microsoft.Office.Interop.Excel._Worksheet.Range' has non-optional arguments which must be provided

What needs to be done?

JohnFx
  • 34,542
  • 18
  • 104
  • 162
P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348

2 Answers2

44
using Excel = Microsoft.Office.Interop.Excel;
...

public void IterateRows(Excel.Worksheet worksheet)
{
    //Get the used Range
    Excel.Range usedRange = worksheet.UsedRange;
    
    //Iterate the rows in the used range
    foreach(Excel.Range row in usedRange.Rows)
    {
        //Do something with the row.
    
        //Ex. Iterate through the row's data and put in a string array
        String[] rowData = new String[row.Columns.Count];
        
        for(int i = 0; i < row.Columns.Count; i++)
            rowData[i] =Convert.ToString(row.Cells[1, i + 1].Value2);
    }
}

This compiles and runs just great for me! I'm using it to extract rows with missing fields to an error log.

Diego Montania
  • 322
  • 5
  • 12
nicholeous
  • 677
  • 1
  • 8
  • 13
  • Should be String[] rowData = new String[row.Columns.Count]; – eomeroff Mar 01 '14 at 19:24
  • Should that foreach line be foreach(Excel.Range row in usedRange.Rows) ? – Rob Koch Jul 16 '14 at 17:13
  • 2
    Note that this method may be too slow for a lot of uses, converting the entire range to an object array prior to iterating will speed things up. – Dave Ross Jul 07 '17 at 14:10
  • Got: 'Could not load type 'System.Runtime.InteropServices.ComTypes.IEnumerator' from assembly 'System.Private.CoreLib...' when I try to iterate over the usedRange.Rows – micahhoover Nov 16 '21 at 21:23
18

I presume you are actually looking for the last used row. In that case you need to write it like this:

Range UsedRange = worksheet.UsedRange;
int lastUsedRow = UsedRange.Row + UsedRange.Rows.Count - 1;
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490