Spaces:
Sleeping
Sleeping
Update app.py
Browse files15 unmodified lines16171819202122232 unmodified lines2627282930313233343536373839404142434413 unmodified lines585960616263646566676869707172737475767778798081828384858687888990919293949596975 unmodified lines1031041051061071081091 unmodified line11111211311411511611711811912012112212312412512612712812913013113213313413515 unmodified linesreturn None, "模板高度必須是數字!"files = file_objs if isinstance(file_objs, list) else [file_objs]# 1. 檔案排序 (OF- > DF- > SF- > PF-)prefix_priority = {"OF-": 1, "DF-": 2, "SF-": 3, "PF-": 4}def sort_key(f):name = os.path.basename(f.name).upper()2 unmodified linesreturn (99, name)files.sort(key=sort_key)if not os.path.exists(TEMPLATE_FILE):return None, f"找不到模板檔案:{TEMPLATE_FILE}"try:temp_wb = openpyxl.load_workbook(TEMPLATE_FILE)temp_ws = temp_wb.worksheets[0]out_wb = openpyxl.Workbook()out_ws = out_wb.activeout_ws.title = "合併報表"# --- A. 複製模板欄寬 ---for i in range(1, 30):col_l = get_column_letter(i)if col_l in temp_ws.column_dimensions:out_ws.column_dimensions[col_l].width = temp_ws.column_dimensions[col_l].width13 unmodified linesrecords = []start_row_idx = row[0].row + 4for r_idx in range(start_row_idx, start_row_idx + 10):# 跳過原始檔 B 欄,讀取 A + C~U 欄year_val = ws.cell(row=r_idx, column=1).valuedata_row = [ws.cell(row=r_idx, column=c).value for c in range(3, 22)]records.append([year_val] + data_row)file_funds_data.append({"name": fund_name, "data": records})# 寫入新工作表for fund in file_funds_data:# --- B. 複製模板每一列、每一格的完整樣式與列高 ---for r in range(1, template_height + 1):target_row = current_base_row + r - 1# 複製列高if r in temp_ws.row_dimensions:out_ws.row_dimensions[target_row].height = temp_ws.row_dimensions[r].heightfor c in range(1, 26):s_cell = temp_ws.cell(row=r, column=c)t_cell = out_ws.cell(row=target_row, column=c)# 非數據區複製內容 (含標題、備註、表頭)if not (5 <= r <= 14):t_cell.value = s_cell.value# 完整深拷貝所有樣式屬性 (確保字型、置中、顏色不跑掉)if s_cell.has_style:t_cell.font = copy(s_cell.font)t_cell.border = copy(s_cell.border)t_cell.fill = copy(s_cell.fill)t_cell.alignment = copy(s_cell.alignment)t_cell.number_format = copy(s_cell.number_format)t_cell.protection = copy(s_cell.protection)# --- C. 套用合併儲存格 ---if temp_ws.merged_cells:for m_range in temp_ws.merged_cells.ranges:if m_range.min_row <= template_height:5 unmodified linesend_column=max_col)# --- D. 填入數據 (從 A 欄開始對正) ---out_ws.cell(row=current_base_row, column=1).value = f"{fund['name']}近10年度收支概況彙總表"for r_idx, row_vals in enumerate(fund['data']):for c_idx, val in enumerate(row_vals):1 unmodified linecurrent_base_row += template_height# 檔案補白if len(file_funds_data) % 2 != 0:current_base_row += template_heightoutput_path = os.path.abspath("Final_Style_Restored_Report.xlsx")out_wb.save(output_path)return output_path, "合併成功!已強制複製列高與字型樣式。"except Exception as e:return None, f"發生錯誤: {str(e)}"# Gradio 介面保持不變with gr.Blocks() as app:gr.Markdown("# 基金報表合併系統 (樣式完全還原版)")with gr.Row():f_in = gr.File(label="上傳原始 Excel", file_count="multiple")h_in = gr.Number(label="模板高度 (您的模板看起來大約是 15 或 16)", value=20)btn = gr.Button("🚀 開始合併並還原樣式", variant="primary")f_out = gr.File(label="下載")status = gr.Textbox(label="狀態")btn.click(process_direct_merge, [f_in, h_in], [f_out, status])15 unmodified lines16171819202122232 unmodified lines262728293031323334353637383913 unmodified lines53545556575859606162636465666768697071727374757677787980818283845 unmodified lines909192939495961 unmodified line989910010110210310410510610710810911011111211311411511611711811912012112212312412512612715 unmodified linesreturn None, "模板高度必須是數字!"files = file_objs if isinstance(file_objs, list) else [file_objs]# 檔案排序邏輯 (OF- > DF- > SF- > PF-)prefix_priority = {"OF-": 1, "DF-": 2, "SF-": 3, "PF-": 4}def sort_key(f):name = os.path.basename(f.name).upper()2 unmodified linesreturn (99, name)files.sort(key=sort_key)try:temp_wb = openpyxl.load_workbook(TEMPLATE_FILE)temp_ws = temp_wb.worksheets[0]out_wb = openpyxl.Workbook()out_ws = out_wb.active# 1. 預先複製欄寬for i in range(1, 31):col_l = get_column_letter(i)if col_l in temp_ws.column_dimensions:out_ws.column_dimensions[col_l].width = temp_ws.column_dimensions[col_l].width13 unmodified linesrecords = []start_row_idx = row[0].row + 4for r_idx in range(start_row_idx, start_row_idx + 10):# 跳過原始檔 B 欄year_val = ws.cell(row=r_idx, column=1).valuedata_row = [ws.cell(row=r_idx, column=c).value for c in range(3, 22)]records.append([year_val] + data_row)file_funds_data.append({"name": fund_name, "data": records})# 寫入資料與樣式for fund in file_funds_data:for r in range(1, template_height + 1):target_row = current_base_row + r - 1# 同步範本列高if r in temp_ws.row_dimensions:out_ws.row_dimensions[target_row].height = temp_ws.row_dimensions[r].heightfor c in range(1, 26):s_cell = temp_ws.cell(row=r, column=c)t_cell = out_ws.cell(row=target_row, column=c)if not (5 <= r <= 14): t_cell.value = s_cell.valueif s_cell.has_style:t_cell.font = copy(s_cell.font)t_cell.border = copy(s_cell.border)t_cell.fill = copy(s_cell.fill)t_cell.alignment = copy(s_cell.alignment)t_cell.number_format = copy(s_cell.number_format)# 套用合併格if temp_ws.merged_cells:for m_range in temp_ws.merged_cells.ranges:if m_range.min_row <= template_height:5 unmodified linesend_column=max_col)# 填入內容out_ws.cell(row=current_base_row, column=1).value = f"{fund['name']}近10年度收支概況彙總表"for r_idx, row_vals in enumerate(fund['data']):for c_idx, val in enumerate(row_vals):1 unmodified linecurrent_base_row += template_height# --- 關鍵修正:補空白列時也要同步範本列高 ---if len(file_funds_data) % 2 != 0:for r in range(1, template_height + 1):target_row = current_base_row + r - 1if r in temp_ws.row_dimensions:out_ws.row_dimensions[target_row].height = temp_ws.row_dimensions[r].height# 如果希望補位的空白頁也有表格框線,可以在此處加入複製 border 的代碼current_base_row += template_heightoutput_path = os.path.abspath("Final_Height_Sync_Report.xlsx")out_wb.save(output_path)return output_path, f"合併成功!已將高度設為 {template_height} 並同步空白列高。"except Exception as e:return None, f"發生錯誤: {str(e)}"# Gradio UI 保持不變with gr.Blocks() as app:gr.Markdown("# 基金報表合併系統 (列高完全同步版)")with gr.Row():f_in = gr.File(label="上傳 Excel", file_count="multiple")h_in = gr.Number(label="設定模板高度 (目前您是 19 列)", value=19)btn = gr.Button("🚀 開始一鍵生成", variant="primary")f_out = gr.File(label="下載結果")status = gr.Textbox(label="狀態")btn.click(process_direct_merge, [f_in, h_in], [f_out, status])
app.py+24-32