简体   繁体   English

无法使用c#从Excel文件中删除空行

[英]Unable to delete empty rows from Excel file using c#

I am trying to delete empty rows from my Excel. 我试图从我的Excel中删除空行。

I have tried seeing other examples and even tried implementing but it doesn't work.What I need to do is delete an entire row If the first cell of that row is empty. 我试过看其他的例子,甚至尝试实现,但它不起作用。我需要做的是删除整行如果该行的第一个单元格为空。

Here is what I have tried: 这是我尝试过的:

ReadExcel.cs: ReadExcel.cs:

Excel.Application excelApp = new Excel.Application();
Excel.Workbook workbook = excelApp.Workbooks.Open(fileLocation)
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.ActiveSheet;
Excel.Range usedRange = worksheet.UsedRange;
int rowCount = worksheet.UsedRange.Rows.Count;
int colCount = worksheet.UsedRange.Columns.Count;

        for (int i = 1; i <= rowCount; i++)
        {
      if (usedRange.Cells[1, 1] == null)
             {
                // Delete entire row if first cell is empty
                usedRange.Cells[1, 1]).EntireRow.Delete(null);
            }

            workbook.Save();
        }

The problem that I face is that it keeps on looping through the excel and does not follow the if condition even when the cell is null 我面临的问题是它继续循环遍历excel并且即使在单元格为空时也不遵循if条件

First you code is always deleting row 1. You should be moving through all the rows. 首先,您的代码总是删除第1行。您应该遍历所有行。 Second whenever deleting always start at the end and move towards the beginning otherwise you can miss rows. 第二,每当删除总是从最后开始并向开头移动,否则你可能会错过行。 The issue is if you delete row 4 then row 5 becomes 4 and you skip row 5. See code below 问题是如果删除第4行,则第5行变为4,然后跳过第5行。请参阅下面的代码

        for (int i = rowCount - 1; i >= 1; i--)
        {
             if (usedRange.Cells[i, 1] == null)
             {
                // Delete entire row if first cell is empty
                usedRange.Cells[i, 1]).EntireRow.Delete(null);
             }

        }
        workbook.Save();

Finally this works: 最后这个工作:

        Excel.Application excelApp = new Excel.Application();
        Excel.Workbook workbook = excelApp.Workbooks.Open(fileLocation, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];
        Excel.Range usedRange = worksheet.UsedRange;
        int rowCount = usedRange.Rows.Count;
        int colCount = usedRange.Columns.Count;

        for (int i = rowCount; i >= 1; i--)
        {
            if (string.IsNullOrEmpty((worksheet.Cells[i, 1]).Text.ToString()))
            {
                // Delete entire row if first cell is empty
                (worksheet.Cells[i, 1]).EntireRow.Delete();
            }

}
        workbook.Save();

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

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