问题描述:我想利用openpyxl帮忙自动筛选出表格的属于B3,且在当月离职的员工的信息,并形成新的表格。但在运行时报错,无法识别“B3”,请教各位指点下,万分感谢!!
代码如下:
import openpyxl
from openpyxl.worksheet.filters import FilterColumn, CustomFilter
wb = openpyxl.load_workbook("C:\Users\Jake\Desktop\Multek人员信息.xlsx")
ws = wb["离职"]
from datetime import datetime
current_month = datetime.now().month
ws.auto_filter.ref = "A1:DH4193"
ws.auto_filter.add_filter_column(7, CustomFilter(operator="equal", val="BT"))
ws.auto_filter.add_filter_column(109, CustomFilter(operator="equal", val=current_month))
new_wb = openpyxl.Workbook()
new_ws = new_wb.active
new_ws.title = f"{current_month}月具体名单"
for row in ws.iter_rows(min_row=1, min_col=1):
if row[0].row == 1 or row[0].value: # 如果是第一行或者有值(说明通过了筛选)
new_ws.append([cell.value for cell in row]) # 把整行的值添加到新的工作簿中
new_wb.save(f"C:\Users\Jake\Desktop\{current_month}月具体名单.xlsx")
#运行后会报错,显示单元格中“B3”不符合格式?
报错如下:D:\Python\openpyxl\worksheet_reader.py:223: UserWarning: Cell CU200 is marked as a date but the serial value 13680161956 is outside the limits for dates. The cell will be treated as an error.
warn(msg)
Traceback (most recent call last):
File "D:\python_work\test_2.py", line 15, in
ws.auto_filter.add_filter_column(7, CustomFilter(operator="equal", val="BT"))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Python\openpyxl\worksheet\filters.py", line 184, in init
self.val = val
^^^^^^^^
File "D:\Python\openpyxl\worksheet\filters.py", line 165, in set
raise ValueError("Value must be either numerical or a string containing a wildcard")
ValueError: Value must be either numerical or a string containing a wildcard
请教各位帮帮忙,万分感谢
根据你提供的代码可以看出有两个问题:
所以,你需要将代码的第13行和第14行修改为以下代码:
ws.auto_filter.ref = "A1:DH4193"
ws.auto_filter.add_filter_column(1, CustomFilter(operator="equal", val="B3"))
ws.auto_filter.add_filter_column(109, CustomFilter(operator="equal", val=str(current_month)))