import pandas as pd from openpyxl import load_workbook from openpyxl.styles import Font, PatternFill, Alignment, Border, Side from openpyxl.utils import get_column_letter SOURCE_FILE = "accountability_combined.xlsx" OUTPUT_FILE = "sheet_kits_for_destruction.xlsx" SHEET_NAME = "Kits for destruction" DATE_COLUMNS = { "Orig Exp Date", "Exp Date", "Rcv Date", "Date Asgn", "Disp Date", "Date Ret", "Destroyed", } COLUMN_WIDTHS = { "Site": 14, "Med ID": 10, "Lot No.": 12, "Orig Exp Date": 16, "Exp Date": 14, "Rcv Date": 14, "Rcpt User": 22, "Subject ID": 14, "Qty Asgn": 9, "IRT Tx": 8, "Date Asgn": 14, "Asgn User": 20, "Disp Status": 16, "Disp Date": 14, "Qty Disp": 9, "Disp User": 20, "Qty Ret": 10, "Date Ret": 14, "Ret User": 18, "Destroyed": 14, "Basket No.": 12, } df = pd.read_excel(SOURCE_FILE) for col in DATE_COLUMNS: if col in df.columns: df[col] = pd.to_datetime(df[col], errors="coerce") # Filter: no basket AND (Date Ret filled OR Disp Status == NOT DISPENSED) mask = ( df["Basket No."].isna() & ( df["Date Ret"].notna() | (df["Disp Status"].str.upper() == "NOT DISPENSED") ) ) filtered = df[mask].copy().sort_values(["Site", "Date Ret"], ascending=[True, True]) filtered = filtered.drop(columns=["Destroyed", "Basket No."]).reset_index(drop=True) print(f"Kits for destruction: {len(filtered)}") filtered.to_excel(OUTPUT_FILE, index=False, sheet_name=SHEET_NAME) # Formatting wb = load_workbook(OUTPUT_FILE) ws = wb[SHEET_NAME] header_fill = PatternFill("solid", start_color="595959") # dark grey header_font = Font(bold=True, color="FFFFFF", name="Arial", size=10) row_font = Font(name="Arial", size=10) basket_fill = PatternFill("solid", start_color="FFE0E0") # light red for empty Basket No. thin = Side(style="thin", color="000000") border = Border(left=thin, right=thin, top=thin, bottom=thin) headers = [cell.value for cell in ws[1]] for cell in ws[1]: cell.fill = header_fill cell.font = header_font cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=False) cell.border = border for row in ws.iter_rows(min_row=2, max_row=ws.max_row): for cell in row: col_name = headers[cell.column - 1] if cell.column <= len(headers) else None cell.font = row_font cell.border = border cell.alignment = Alignment(horizontal="center") if col_name in DATE_COLUMNS: cell.number_format = "DD-MMM-YYYY" if col_name == "Basket No.": cell.fill = basket_fill for cell in ws[1]: width = COLUMN_WIDTHS.get(cell.value, 14) ws.column_dimensions[get_column_letter(cell.column)].width = width ws.auto_filter.ref = ws.dimensions ws.freeze_panes = "A2" wb.save(OUTPUT_FILE) print(f"Saved: {OUTPUT_FILE} (sheet: '{SHEET_NAME}')")