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,209
  • 18
  • 103
  • 160
P.Brian.Mackey
  • 41,438
  • 63
  • 228
  • 337

2 Answers2

41
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.

Tabish Usman
  • 2,980
  • 2
  • 16
  • 15
nicholeous
  • 627
  • 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) ? – Robert 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
  • 587,191
  • 41
  • 1,025
  • 1,442