代码之家  ›  专栏  ›  技术社区  ›  Inception

如果openpyxl中整行为空,则上移单元格

  •  1
  • Inception  · 技术社区  · 6 年前

    如果整行中没有值,我希望删除整行(上移单元格)。我在用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)
    

    感谢您的帮助!

    2 回复  |  直到 6 年前
        1
  •  0
  •   Charlie Clark    6 年前

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

    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)
    
        2
  •  0
  •   Inception    6 年前

    感谢查理·克拉克的帮助,我想出了一个可行的解决方案,如果我能改进一下,请告诉我:

    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]