简体   繁体   中英

Unable to delete empty rows from Excel file using c#

I am trying to delete empty rows from my 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:

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

First you code is always deleting row 1. You should be moving through all the rows. 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

        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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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