简体   繁体   English

如果满足条件,如何使用 openpyxl python 删除 excel 中的特定行

[英]How to delete specific rows in excel with openpyxl python if condition is met

Using openpyxl I am creating python script that will loop through the rows of data and find rows in which some of the column are empty - these will be deleted.使用 openpyxl 我正在创建 python 脚本,该脚本将遍历数据行并查找其中某些列为空的行 - 这些将被删除。 The range of rows is 3 to 1800.行的范围是 3 到 1800。

I am not excatly sure how to delete these row - please see code I have come up with so far.我不确定如何删除这些行 - 请参阅我到目前为止提出的代码。 What I was trying to achieve is to iterate through the rows and check if columns 4, 7 values are set to None.我试图实现的是遍历行并检查第 4、7 列的值是否设置为无。 If True I wanted to return row number into suitable collection (need advise which one would be best for this) and then create another loop that would delete specific row number reversed as I don't want change the structure of the file by deleting rows with data.如果为真,我想将行号返回到合适的集合中(需要建议哪一个最适合这个),然后创建另一个循环来删除特定的行号,因为我不想通过删除行来更改文件的结构数据。

I believe there may be easier function to do this but could not find this particular answer.我相信 function 可能更容易做到这一点,但找不到这个特定的答案。

for i in worksheet.iter_rows(min_row=3, max_row=1800):
emp_id = i[4]
full_name = i[7]
if emp_id.value == None and full_name.value == None:
print(worksheet[i].rows)
rows_to_delete.append(i)

Your iteration looks good.你的迭代看起来不错。

OpenPyXl offers worksheet.delete_rows(idx, amt=1) where idx is the index of the first row to delete (1-based) and amt is the amount of rows to delete beyond that index. OpenPyXl 提供worksheet.delete_rows(idx, amt=1)其中idx是要删除的第一行的索引(从 1 开始), amt是要删除的超出该索引的行数。

So worksheet.delete_rows(3, 4) will delete rows 3, 4, 5, and 6 and worksheet.delete_rows(2, 1) will just delete row 2.因此worksheet.delete_rows(3, 4)将删除第 3、4、5 和 6 行,而worksheet.delete_rows(2, 1)将只删除第 2 行。

In your case, you'd probably want to do something like worksheet.delete_rows(i, 1) .在您的情况下,您可能想要执行类似worksheet.delete_rows(i, 1)的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM