Search code examples
pythonexcelrowopenpyxl

Shift cells up if entire row is empty in Openpyxl


I want the entire row to be removed(shift cells up) if there are no values in the entire row. I'm using Openpyxl.

My code:

for row in range(1, ws1.max_row):
  flag = 0
  for col in range(1, 50):
    if ws1.cell(row, col).value is not None:
      flag = 1

  if flag == 0:
    ws1.delete_rows(row, 1)

The rows are not getting deleted in the above case.

I tried using iter_rows function to do the same and it gives me:

TypeError: '>' not supported between instances of 'tuple' and 'int'

for row in ws1.iter_rows(min_row = 1, max_col=50, max_row = ws1.max_row):
  flag = 0
  for cell in row:
    if cell.value is not None:
      flag = 1

  if flag == 0:
    ws1.delete_rows(row, 1)

Help is appreciated!


Solution

  • The following is a generic approach to finding and then deleting empty rows.

    empty_rows = []
    for idx, row in enumerate(ws.iter_rows(max_col=50), start=1):
    
      empty = not any((cell.value for cell in row))
    
      if empty:
        empty_rows.append(idx)
    
    for row_idx in reversed(empty_rows):
      ws.delete_rows(row_idx, 1)