use*_*631 0 python python-3.x openpyxl
我想从 excel 文件中删除行,知道这些值。我使用 openpyxl:
key_values_list 是带有数字的列表(所有都存在于 excel 文件中,列上)
wb = load_workbook(src)
sheet = wb['Sheet 1']
for i in range(2, sheet.max_row + 1):
if sheet.cell(row=i, column=1).value in key_values_list:
sheet.delete_rows(i, 1)
wb.save(src)
Run Code Online (Sandbox Code Playgroud)
上面的代码不会删除所有对应的行
在 for 循环中删除直接元素时总会遇到问题。考虑具有 12 行及其各自行值的工作表的以下代码:
for i in range(1, sh.max_row + 1):
print(sh.cell(row=i, column=1).value)
# 1 .. 12
Run Code Online (Sandbox Code Playgroud)
现在看看当你开始删除东西时会发生什么:
for i in range(1, sh.max_row + 1):
if sh.cell(row=i, column=1).value in [5,6,7]:
sh.delete_rows(i, 1)
print(f'i = {i}\tcell value (i, 1) is {sh.cell(row=i, column=1).value}')
# i = 1 cell value (i, 1) is 1
# i = 2 cell value (i, 1) is 2
# i = 3 cell value (i, 1) is 3
# i = 4 cell value (i, 1) is 4
# i = 5 cell value (i, 1) is 5
# i = 6 cell value (i, 1) is 7
# i = 7 cell value (i, 1) is 9
# i = 8 cell value (i, 1) is 10
# i = 9 cell value (i, 1) is 11
# i = 10 cell value (i, 1) is 12
# i = 11 cell value (i, 1) is None
# i = 12 cell value (i, 1) is None
Run Code Online (Sandbox Code Playgroud)
您可以看到,在 期间i in [5, 6, 7],行的移动从第 6 行开始,因为第 5 行已被删除,使原始第 6 行成为新行 5、原始第 7 行新行 6...等等。所以在下一次迭代中i = 6,单元格实际上是引用原始数据中第 7 行的值。您有效地跳过了第 6 行的迭代。
最简单的答案是使用while循环,而不是for:
i = 1
while i <= sh.max_row:
print(f'i = {i}\tcell value (i, 1) is {sh.cell(row=i, column=1).value}')
if sh.cell(row=i, column=1).value in [5,6,7]:
sh.delete_rows(i, 1)
# Note the absence of incremental. Because we deleted a row, we want to stay on the same row because new data will show in the next iteration.
else:
i += 1
# Because the check failed, we can safely increment to the next row.
# i = 1 cell value (i, 1) is 1
# i = 2 cell value (i, 1) is 2
# i = 3 cell value (i, 1) is 3
# i = 4 cell value (i, 1) is 4
# i = 5 cell value (i, 1) is 5 # deleted
# i = 5 cell value (i, 1) is 6 # deleted
# i = 5 cell value (i, 1) is 7 # deleted
# i = 5 cell value (i, 1) is 8
# i = 6 cell value (i, 1) is 9
# i = 7 cell value (i, 1) is 10
# i = 8 cell value (i, 1) is 11
# i = 9 cell value (i, 1) is 12
# verify the data has been deleted
for i in range(1, sh.max_row +1):
print(sh.cell(row=i, column=1).value)
# 1
# 2
# 3
# 4
# 8
# 9
# 10
# 11
# 12
Run Code Online (Sandbox Code Playgroud)
你现在可以看到虽然i没有达到 12,但每一行都被迭代了,因为i=5已经被处理了三次。
如果出于某种原因必须使用for循环进行迭代,则可能需要考虑一些替代方法,例如遍历副本或向后执行