import pandas as pd import streamlit as st from datetime import datetime, timedelta import matplotlib.pyplot as plt import io import base64 import math from matplotlib.backends.backend_pdf import PdfPages from matplotlib.patches import Rectangle # Replaced FancyBboxPatch # --- Constants --- SPLIT_TIME = "17:30" BUSINESS_START = "09:30" BUSINESS_END = "01:30" BORDER_COLOR = '#CCCCCC' # Light gray for dotted border DATE_COLOR = '#A9A9A9' A5_WIDTH_INCH = 5.83 A5_HEIGHT_INCH = 8.27 def process_schedule(file): """处理上传的 Excel 文件,生成排序和分组后的打印内容""" try: # 读取 Excel,跳过前 8 行 df = pd.read_excel(file, skiprows=8) # 提取所需列 (G9, H9, J9) df = df.iloc[:, [6, 7, 9]] # G, H, J 列 df.columns = ['Hall', 'StartTime', 'EndTime'] # 清理数据 df = df.dropna(subset=['Hall', 'StartTime', 'EndTime']) # 转换影厅格式为 "#号" 格式 df['Hall'] = df['Hall'].str.extract(r'(\d+)号').astype(str) + ' ' # 保存原始时间字符串用于诊断 df['original_end'] = df['EndTime'] # 转换时间为 datetime 对象 base_date = datetime.today().date() df['StartTime'] = pd.to_datetime(df['StartTime']) df['EndTime'] = pd.to_datetime(df['EndTime']) # 设置基准时间 business_start = datetime.strptime(f"{base_date} {BUSINESS_START}", "%Y-%m-%d %H:%M") business_end = datetime.strptime(f"{base_date} {BUSINESS_END}", "%Y-%m-%d %H:%M") # 处理跨天情况 if business_end < business_start: business_end += timedelta(days=1) # 标准化所有时间到同一天 for idx, row in df.iterrows(): end_time = row['EndTime'] if end_time.hour < 9: df.at[idx, 'EndTime'] = end_time + timedelta(days=1) if row['StartTime'].hour >= 21 and end_time.hour < 9: df.at[idx, 'EndTime'] = end_time + timedelta(days=1) # 筛选营业时间内的场次 df['time_for_comparison'] = df['EndTime'].apply( lambda x: datetime.combine(base_date, x.time()) ) df.loc[df['time_for_comparison'].dt.hour < 9, 'time_for_comparison'] += timedelta(days=1) valid_times = ( ((df['time_for_comparison'] >= datetime.combine(base_date, business_start.time())) & (df['time_for_comparison'] <= datetime.combine(base_date + timedelta(days=1), business_end.time()))) ) df = df[valid_times] # 按散场时间排序 df = df.sort_values('EndTime') # 分割数据 split_time = datetime.strptime(f"{base_date} {SPLIT_TIME}", "%Y-%m-%d %H:%M") split_time_for_comparison = df['time_for_comparison'].apply( lambda x: datetime.combine(base_date, split_time.time()) ) part1 = df[df['time_for_comparison'] <= split_time_for_comparison].copy() part2 = df[df['time_for_comparison'] > split_time_for_comparison].copy() # 格式化时间显示 for part in [part1, part2]: part['EndTime'] = part['EndTime'].dt.strftime('%-I:%M') # 精确读取C6单元格 date_df = pd.read_excel( file, skiprows=5, # 跳过前5行(0-4) nrows=1, # 只读1行 usecols=[2], # 第三列(C列) header=None # 无表头 ) date_cell = date_df.iloc[0, 0] try: # 处理不同日期格式 if isinstance(date_cell, str): date_str = datetime.strptime(date_cell, '%Y-%m-%d').strftime('%Y-%m-%d') else: date_str = pd.to_datetime(date_cell).strftime('%Y-%m-%d') except: date_str = datetime.today().strftime('%Y-%m-%d') return part1[['Hall', 'EndTime']], part2[['Hall', 'EndTime']], date_str except Exception as e: st.error(f"处理文件时出错: {str(e)}") return None, None, None def create_print_layout(data, title, date_str): """创建符合新设计要求的打印布局 (PNG 和 PDF)""" if data.empty: return None # --- 1. 初始化 Figure --- fig = plt.figure(figsize=(A5_WIDTH_INCH, A5_HEIGHT_INCH), dpi=300) # 使用整个figure区域,手动控制所有边距 fig.subplots_adjust(left=0, right=1, top=1, bottom=0) plt.rcParams['font.family'] = 'sans-serif' plt.rcParams['font.sans-serif'] = ['Arial Unicode MS'] # --- 2. 数据准备和布局计算 --- total_items = len(data) num_cols = 3 data_rows = math.ceil(total_items / num_cols) if data_rows == 0: data_rows = 1 # 避免除以零 # 为header分配固定高度 (占总高度的8%), 剩余为数据区 header_height_norm = 0.08 data_area_height_norm = 1.0 - header_height_norm # 每个数据单元格的尺寸 (标准化坐标, 0-1) cell_height_norm = data_area_height_norm / data_rows cell_width_norm = 1.0 / num_cols # 根据单元格高度计算留白距离 (高度的 1/4 作为边距) # 这将被用作单元格内部的padding spacing_norm_y = cell_height_norm / 4 spacing_norm_x = cell_width_norm / 4 # 对称的边距 # 准备数据 (Z字形排序) data_values = data.values.tolist() while len(data_values) % num_cols != 0: data_values.append(['', '']) rows_per_col_layout = math.ceil(len(data_values) / num_cols) sorted_data = [['', '']] * len(data_values) for i, item in enumerate(data_values): if item[0] and item[1]: row_in_col = i % rows_per_col_layout col_idx = i // rows_per_col_layout new_index = row_in_col * num_cols + col_idx if new_index < len(sorted_data): sorted_data[new_index] = item # --- 3. 绘制元素 --- # 绘制页眉 (日期和标题) ax_date = fig.add_axes([0, data_area_height_norm, 1, header_height_norm]) ax_date.text(0.02, 0.5, f"{date_str} {title}", fontsize=12, color=DATE_COLOR, fontweight='bold', ha='left', va='center', transform=ax_date.transAxes) ax_date.set_axis_off() # 动态计算主字体大小,使其适应单元格高度 # 1英寸 = 72点。字体大小占单元格高度的40%左右 base_fontsize = (cell_height_norm * A5_HEIGHT_INCH) * 72 * 0.4 # 绘制数据单元格 for idx, (hall, end_time) in enumerate(sorted_data): if hall and end_time: row_grid = idx // num_cols col_grid = idx % num_cols # 计算单元格(Axes)的位置和尺寸 ax_left = col_grid * cell_width_norm # Y坐标从下往上,所以要从数据区顶部开始往下减 ax_bottom = data_area_height_norm - (row_grid + 1) * cell_height_norm ax = fig.add_axes([ax_left, ax_bottom, cell_width_norm, cell_height_norm]) ax.set_axis_off() # 要求 2 & 3: 创建点状虚线边框和呼吸感 # 通过在Axes内部绘制一个稍小的矩形来实现 border_padding_x = spacing_norm_x / 2 border_padding_y = spacing_norm_y / 2 border_rect = Rectangle( (border_padding_x, border_padding_y), # 左下角坐标 (x,y) 1 - 2 * border_padding_x, # 宽度 1 - 2 * border_padding_y, # 高度 transform=ax.transAxes, edgecolor=BORDER_COLOR, facecolor='none', linestyle=':', # 点状虚线 linewidth=2 # 让点更明显 ) ax.add_patch(border_rect) # 要求 4: 在左上角添加序号 ax.text(border_padding_x + 0.02, 1 - border_padding_y - 0.02, str(idx + 1), fontsize=base_fontsize * 0.3, # 序号字体较小 color='grey', ha='left', va='top', transform=ax.transAxes) # 要求 3: 居中显示主要文本 display_text = f"{hall}{end_time}" ax.text(0.5, 0.5, display_text, fontsize=base_fontsize, fontweight='bold', ha='center', va='center', transform=ax.transAxes) # --- 4. 保存到内存 --- # 保存为 PNG png_buffer = io.BytesIO() fig.savefig(png_buffer, format='png', bbox_inches='tight', pad_inches=0.02) png_buffer.seek(0) png_base64 = base64.b64encode(png_buffer.getvalue()).decode() # 保存为 PDF pdf_buffer = io.BytesIO() with PdfPages(pdf_buffer) as pdf: pdf.savefig(fig, bbox_inches='tight', pad_inches=0.02) pdf_buffer.seek(0) pdf_base64 = base64.b64encode(pdf_buffer.getvalue()).decode() plt.close(fig) return { 'png': f'data:image/png;base64,{png_base64}', 'pdf': f'data:application/pdf;base64,{pdf_base64}' } def display_pdf(base64_pdf): """在Streamlit中嵌入显示PDF""" pdf_display = f'' return pdf_display # --- Streamlit 界面 (无变化) --- st.set_page_config(page_title="散厅时间快捷打印", layout="wide") st.title("散厅时间快捷打印") uploaded_file = st.file_uploader("上传【放映场次核对表.xls】文件", type=["xls"]) if uploaded_file: part1, part2, date_str = process_schedule(uploaded_file) if part1 is not None and part2 is not None: # 生成包含 PNG 和 PDF 的字典 part1_output = create_print_layout(part1, "A", date_str) part2_output = create_print_layout(part2, "C", date_str) col1, col2 = st.columns(2) with col1: st.subheader("白班散场预览(时间 ≤ 17:30)") if part1_output: tab1_1, tab1_2 = st.tabs(["PDF 预览", "PNG 预览"]) with tab1_1: st.markdown(display_pdf(part1_output['pdf']), unsafe_allow_html=True) with tab1_2: st.image(part1_output['png']) else: st.info("白班部分没有数据") with col2: st.subheader("夜班散场预览(时间 > 17:30)") if part2_output: tab2_1, tab2_2 = st.tabs(["PDF 预览", "PNG 预览"]) with tab2_1: st.markdown(display_pdf(part2_output['pdf']), unsafe_allow_html=True) with tab2_2: st.image(part2_output['png']) else: st.info("夜班部分没有数据")