Home > Mobile >  How to get Excel range for only filled Rows with Interop Excel?
How to get Excel range for only filled Rows with Interop Excel?

Time:12-06

so I've read with Interop Excel from every Row the data.

The problem is that some excel files have a lot of empty rows for example I have an file that has like 2000 rows but only the first 100 have data.

But Interop is not reading the first 100 which are filled, he is reading the whole 2000 rows.

To loop through every row I have this code:

Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

                Microsoft.Office.Interop.Excel.Workbook excelBook = excelApp.Workbooks.Open(ExcelPath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                Microsoft.Office.Interop.Excel.Worksheet excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelBook.Worksheets.get_Item(1); ;
                Microsoft.Office.Interop.Excel.Range excelRange = excelSheet.UsedRange;

and the loop condition:

for (rowCnt = 2; rowCnt <= excelRange.Rows.Count; rowCnt  )

excelrange received all 2000 rows but he should recive only filled rows.

What I have tried is this If statement after the for condition:

  if ( String.IsNullOrEmpty( (string)(excelRange.Cells[rowCnt, 1] as Microsoft.Office.Interop.Excel.Range).Value2))
                    {
                        excelSheet.Cells[rowCnt, 1].EntireRow.Delete(null);

                    }

but this is not working.

Is it possible to get the range for only filled rows?

CodePudding user response:

In your code, you're only checking if fist column of each row is empty. In that case, you can check like this:

if ((excelRange.Cells[rowCnt, 1] as Microsoft.Office.Interop.Excel.Range).Value == null)
{
     //delete here
}

If you want to check if every column in row is empty and then delete row, you can do it with something like this:

for (int rowCnt = 2; rowCnt <= excelRange.Rows.Count; rowCnt  )
{
    bool rowEmpty = true;
    // check every cell in this row
    for (int colCnt = 1; colCnt <= excelRange.Cells.Count; colCnt  )
    {
        if ((excelRange.Cells[rowCnt, colCnt] as Microsoft.Office.Interop.Excel.Range).Value != null)
        {
            rowEmpty = false;
            break;
        }
    }
    if (rowEmpty) 
    {
        //delete it
    }
}
  • Related