Search code examples
pythonopenpyxl

openpyxl delete_rows doesn't completely remove rows if row height is set


Any suggestions? If I ever the row height in openpyxl, delete_rows will appear to remove the rows, but when I save and open in Excel, the rows are empty but not all row information is removed. The scroll bar still scrolls to where the last row was prior to deleting. So "ghosts" of the empty rows remain. Sample code:

from openpyxl import Workbook

# Create a new workbook and select the active sheet
wb = Workbook()
ws = wb.active


# Write values into the cells
for row in range(1, 101):
    for col in range(1, 6):
        cell = ws.cell(row=row, column=col)
        cell.value = f"Cell {row}-{col}"

# Set row height
for row in ws.iter_rows():
    ws.row_dimensions[row[0].row].height = 14.4

# Unset row height
for row in ws.iter_rows():
    ws.row_dimensions[row[0].row].height = None

# Delete the rows
ws.delete_rows(35, 100-35)

# Save the workbook
wb.save('test.xlsx')
  1. If I comment out both row height loops, it works correctly.
  2. If either loop is included, remnants of the empty rows remain.

Solution

  • Yes, the delete clears the cells however as the row dimensions have been adjusted (by changing the height) they now exist in the Sheet profile.
    The row delete function does not remove that from the Sheet. The result being that the workbook retains the rows to 100 defined in the Sheet with those above row 35 having no cell details.

    You can fix this by deleting the row dimensions too.

    for x in range(36, 101):
        del ws.row_dimensions[x]
    

    Of course deleting the row dimension instead of setting to None would also affect the same change;

    # Unset row height
    for row in ws.iter_rows():
        # ws.row_dimensions[row[0].row].height = None
        del ws.row_dimensions[row[0].row]