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

前端 未结 3 1072
误落风尘
误落风尘 2020-12-28 16:10

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 work

相关标签:
3条回答
  • 2020-12-28 16:47
    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.

    0 讨论(0)
  • 2020-12-28 17:05

    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;
    
    0 讨论(0)
  • 2020-12-28 17:06

    Have a look at the UsedRange property in Excel.

    0 讨论(0)
提交回复
热议问题