简体   繁体   English

如何使用 Interop Excel 获取仅填充行的 Excel 范围?

[英]How to get Excel range for only filled Rows with Interop Excel?

so I've read with Interop Excel from every Row the data.所以我从每一行数据中读取了 Interop Excel。

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.问题是一些 excel 文件有很多空行,例如我有一个大约有 2000 行的文件,但只有前 100 行有数据。

But Interop is not reading the first 100 which are filled, he is reading the whole 2000 rows.但是 Interop 没有读取已填充的前 100 行,他正在读取整个 2000 行。

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. excelrange收到了所有 2000 行,但他应该只收到填充的行。

What I have tried is this If statement after the for condition:我试过的是在 for 条件之后的 If 语句:

  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?是否可以只获取填充行的范围?

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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM