如果 Openpyxl 中整行为空,则向上移动单元格

Shift cells up if entire row is empty in Openpyxl

如果整行中没有值,我希望删除整行(向上移动单元格)。我正在使用 Openpyxl。

我的代码:

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)

在上述情况下,行没有被删除。

我尝试使用 iter_rows 函数来做同样的事情,它给了我:

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)

感谢帮助!

感谢 Charlie Clark 的帮助,这是我想出的一个可行的解决方案,如果我可以对其进行任何改进,请告诉我:

i = 1
emptyRows = []
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:
    emptyRows.append(i)

  i += 1

for x in emptyRows:
  ws1.delete_rows(x, 1)
  emptyRows[:] = [y - 1 for y in emptyRows]

以下是查找空行然后删除空行的通用方法。

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)