如果单元格包含当前月份,如何删除行?

How do I delete rows if the cells contain the current month?

如果单元格包含当前月份,则删除该行。

例如 excel sheet,之前:

2021 年 3 月 11 日第 1 行第 11 行
25/10/2021 第 2 行第 22
30/10/2021 第 3 行第 33
2021 年 2 月 11 日第 4 行第 44 行
2021 年 10 月 30 日第 5 行第 55 行
2021 年 1 月 11 日第 6 行第 66 行
30/10/2021 第 7 行第 77

之后:

25/10/2021 第 2 行第 22
30/10/2021 第 3 行第 33
2021 年 10 月 30 日第 5 行第 55 行
30/10/2021 第 7 行第 77

我试过这个脚本:

from openpyxl import load_workbook
from datetime import date

wb = load_workbook('file1.xlsx')
ws = wb['Sheet1']
x = ws.max_row
y = ws.max_column

current_month=date.today().month

for r in range(1, x+1):
    for j in range(1, y+1):
        d=ws.cell(row=x+1-r,column=j)
        if d.is_date and d.value.date() == current.month:
             ws.delete_rows(x+1-r)
             break

wb.save("file2.xlsx")

但是没有任何反应。 如果我更改为 if d.is_date and d.value.date() != current.month:,所有行都将被删除。 我必须在哪里更正?

我假设日期不“等于”它的月份。所以你应该这样做:

if d.is_date and d.value.date().month == current.month:
    ...