如果整行中没有值,我希望删除整行(移位单元格)。我使用的是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)
非常感谢帮助!
答案 0 :(得分:0)
感谢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]
答案 1 :(得分:0)
以下是查找并删除空行的一般方法。
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)