【问题标题】:How do I delete rows if the cells contain the current month?如果单元格包含当前月份,如何删除行?
【发布时间】:2021-12-17 19:58:37
【问题描述】:

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

例如在 excel 表中,之前:

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

之后:

2021 年 10 月 25 日第 2 行第 22 行
2021 年 10 月 30 日第 3 行第 33 行
2021 年 10 月 30 日第 5 行第 55 行
2021 年 10 月 30 日第 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:,所有行都会被删除。 我必须在哪里更正?

【问题讨论】:

  • 日期在哪一列?
  • 第一列。

标签: python excel datetime openpyxl


【解决方案1】:

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

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

【讨论】:

  • 成功了。非常感谢!
  • 另外,从工作表的底部向上工作。
猜你喜欢
  • 1970-01-01
  • 2019-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-27
相关资源
最近更新 更多