C# - How do I iterate all the rows in Excel._Worksheet?

非 Y 不嫁゛ 提交于 2019-11-30 12:49:42

问题


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?


回答1:


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] = row.Cells[1, i + 1].Value2.ToString();
    }
}

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




回答2:


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;



回答3:


Have a look at the UsedRange property in Excel.



来源:https://stackoverflow.com/questions/7727738/c-sharp-how-do-i-iterate-all-the-rows-in-excel-worksheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!