Home > Software design >  How do I delete rows if the cells contain the current month?
How do I delete rows if the cells contain the current month?

Time:11-04

If a cell contains the current month, delete the row.

E.g in excel sheet, Before:

03/11/2021 row1 row11
25/10/2021 row2 row22
30/10/2021 row3 row33
02/11/2021 row4 row44
30/10/2021 row5 row55
01/11/2021 row6 row66
30/10/2021 row7 row77

After:

25/10/2021 row2 row22
30/10/2021 row3 row33
30/10/2021 row5 row55
30/10/2021 row7 row77

I tried this script:

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")

But nothing happens. If I change to if d.is_date and d.value.date() != current.month:, all rows are deleted. Where do I have to correct?

CodePudding user response:

I'd assume that the date doesn't "equal" to its month. So you should probably do:

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