import openpyxl from openpyxl.styles import PatternFill # 创建工作簿 wb = openpyxl.Workbook() ws = wb.active ws.title = "30天排班表" # 设置表头 headers = ["日期", "A1", "A2", "A3", "B1", "B2", "B3", "C", "D", "E", "当日休息人数"] ws.append(headers) # 定义休息日(满足所有约束条件) rest_days = { # 格式: 日期: [(组别,人员), ...] 1: [("A",1), ("C",1)], 2: [("B",1), ("D",1)], 3: [("A",2), ("E",1)], 4: [("B",2)], 5: [("A",1)], 6: [("B",1), ("C",1)], 7: [("A",2), ("D",1)], 8: [("B",2), ("E",1)], 9: [("A",1)], 10:[("B",1)], 11:[("A",2), ("C",1)], 12:[("B",2), ("D",1)], 13:[("A",1), ("E",1)], 14:[("B",1)], 15:[("A",2)], 16:[("B",2), ("C",1)], 17:[("A",3), ("D",1)], 18:[("B",3), ("E",1)], 19:[], 20:[], 21:[("A",3)], 22:[("B",3)], 23:[], 24:[], 25:[("A",3)], 26:[("B",3)], 27:[], 28:[], 29:[("A",3)], 30:[("B",3)] } # 填充数据 for day in range(1, 31): row = [day] + ["W"]*9 # 默认全部工作 rest_count = 0 if day in rest_days: for group, person in rest_days[day]: if group == "A": row[1 + person -1] = "R" elif group == "B": row[4 + person -1] = "R" elif group == "C": row[7] = "R" elif group == "D": row[8] = "R" elif group == "E": row[9] = "R" rest_count += 1 row[-1] = rest_count ws.append(row) # 设置颜色 red_fill = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid") for row in ws.iter_rows(min_row=2, max_row=31): for cell in row[1:10]: # 人员列 if cell.value == "R": cell.fill = red_fill # 调整列宽 for col in range(1, 12): ws.column_dimensions[openpyxl.utils.get_column_letter(col)].width = 8 # 保存文件 wb.save("30天排班表.xlsx") print("排班表已生成:30天排班表.xlsx")