如果满足条件,如何使用openpyxl python删除excel中的特定行 [英] How to delete specific rows in excel with openpyxl python if condition is met

查看:275
本文介绍了如果满足条件,如何使用openpyxl python删除excel中的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用openpyxl,我正在创建python脚本,该脚本将遍历数据行并查找其中某些列为空的行-这些行将被删除.行的范围是3到1800.

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. The range of rows is 3 to 1800.

我不确定如何删除这些行-请参阅到目前为止我提出的代码.我想要达到的目的是遍历行,并检查第4、7列的值是否设置为None.如果为True,我想将行号返回到合适的集合中(需要告知哪一个最适合此操作),然后创建另一个循环,该循环将删除反向的特定行号,因为我不想通过删除行来更改文件的结构数据.

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. 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.

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)

推荐答案

您的迭代看起来不错.

OpenPyXl提供 worksheet.delete_rows(idx,amt = 1),其中 idx 是要删除的第一行的索引(基于1)和 amt是该索引之外要删除的行数.

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.

因此, worksheet.delete_rows(3,4)将删除第3、4、5和6行,而 worksheet.delete_rows(2,1)将仅删除行2.

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(i,1)的事情.

In your case, you'd probably want to do something like worksheet.delete_rows(i, 1).

这篇关于如果满足条件,如何使用openpyxl python删除excel中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆