Spaces:
Sleeping
Sleeping
Update app.py
Browse files16 unmodified lines171819202122234 unmodified lines2829303132333420 unmodified lines555657585960616263646566676869707172737475767778793 unmodified lines83848586878889909192939495969798993 unmodified lines10310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513616 unmodified linesfiles = 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()4 unmodified linesfiles.sort(key=sort_key)if not os.path.exists(TEMPLATE_FILE):return None, f"找不到 {TEMPLATE_FILE}"try:temp_wb = openpyxl.load_workbook(TEMPLATE_FILE)20 unmodified linesfor row in ws.iter_rows():first_val = str(row[0].value) if row[0].value else ""if "彙總表" in first_val or "近10年度" in first_val:fund_name = first_val.replace("近10年度", "").replace("收支概況彙總表", "").replace("行政院國家發展基金", "").strip()records = []# 抓取數據 (假設標題下 4 列開始抓 10 列)for r_offset in range(4, 14):r_idx = row[0].row + r_offsetrow_data = [ws.cell(row=r_idx, column=c).value for c in range(1, 21)]records.append(row_data)file_funds_data.append({"name": fund_name, "data": records})for fund in file_funds_data:# A. 複製模板每一格的樣式與內容for r in range(1, template_height + 1):for c in range(1, 26):s_cell = temp_ws.cell(row=r, column=c)t_row = current_base_row + r - 1t_cell = out_ws.cell(row=t_row, column=c)# 除了數據填入區,其餘複製模板內容if not (4 <= r <= 14):t_cell.value = s_cell.valueif s_cell.has_style:3 unmodified linest_cell.alignment = copy(s_cell.alignment)t_cell.number_format = copy(s_cell.number_format)# B. 強制複製合併儲存格資訊if temp_ws.merged_cells:for m_range in temp_ws.merged_cells.ranges:# 只處理高度內的合併if m_range.min_row <= template_height:min_col, min_row, max_col, max_row = m_range.boundsnew_start_row = current_base_row + min_row - 1new_end_row = current_base_row + max_row - 1# 避開已合併區域,強制執行try:out_ws.merge_cells(start_row=new_start_row,start_column=min_col,3 unmodified linesexcept:pass# C. 填入動態資料 (標題與數據)# 重新修正標題 (第一列)out_ws.cell(row=current_base_row, column=1).value = f"{fund['name']}近10年度收支概況彙總表"# 填入 10 年數據 (第 5 列開始)for r_idx, rec_row in enumerate(fund['data']):for c_idx, val in enumerate(rec_row):out_ws.cell(row=current_base_row + 4 + r_idx, column=c_idx + 1).value = valcurrent_base_row += template_height# 補白if len(file_funds_data) % 2 != 0:current_base_row += template_heightoutput_path = os.path.abspath("Final_Combined_Report.xlsx")out_wb.save(output_path)return output_path, "合併完成,已加強修復合併儲存格格式。"except Exception as e:return None, f"發生錯誤: {str(e)}"with gr.Blocks() as app:gr.Markdown("# 基金報表合併系統 (精準格式修復版)")with gr.Row():f_in = gr.File(label="上傳 Excel", file_count="multiple")h_in = gr.Number(label="設定模板高度 (請嘗試 20 或 22)", 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])16 unmodified lines171819202122234 unmodified lines2829303132333420 unmodified lines55565758596061626364656667686970717273747576777879808182833 unmodified lines878889909192939495969798991001011023 unmodified lines10610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914016 unmodified linesfiles = 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()4 unmodified linesfiles.sort(key=sort_key)if not os.path.exists(TEMPLATE_FILE):return None, f"找不到模板檔案 {TEMPLATE_FILE}"try:temp_wb = openpyxl.load_workbook(TEMPLATE_FILE)20 unmodified linesfor row in ws.iter_rows():first_val = str(row[0].value) if row[0].value else ""if "彙總表" in first_val or "近10年度" in first_val:# 清理基金名稱fund_name = first_val.replace("近10年度", "").replace("收支概況彙總表", "").replace("行政院國家發展基金", "").strip()records = []# 核心修正:直接從 B 欄 (第2欄) 開始抓取資料,避免偏移# 假設您的數據區域在標題下 4 列 (第5列到14列)for r_offset in range(4, 14):r_idx = row[0].row + r_offset# 從第 2 欄 (B) 抓到第 21 欄,確保對齊row_data = [ws.cell(row=r_idx, column=c).value for c in range(2, 22)]records.append(row_data)file_funds_data.append({"name": fund_name, "data": records})for fund in file_funds_data:# A. 複製模板每一格的樣式、內容for r in range(1, template_height + 1):for c in range(1, 26):s_cell = temp_ws.cell(row=r, column=c)t_row = current_base_row + r - 1t_cell = out_ws.cell(row=t_row, column=c)# 除了數據填入區,其餘複製模板內容 (標題、備註等)if not (5 <= r <= 14):t_cell.value = s_cell.valueif s_cell.has_style:3 unmodified linest_cell.alignment = copy(s_cell.alignment)t_cell.number_format = copy(s_cell.number_format)# B. 強制重新套用合併儲存格if temp_ws.merged_cells:for m_range in temp_ws.merged_cells.ranges:if m_range.min_row <= template_height:min_col, min_row, max_col, max_row = m_range.boundsnew_start_row = current_base_row + min_row - 1new_end_row = current_base_row + max_row - 1try:# 先解除可能存在的衝突合併,再重新合併out_ws.merge_cells(start_row=new_start_row,start_column=min_col,3 unmodified linesexcept:pass# C. 填入動態資料# 重新填入大標題 (A1)out_ws.cell(row=current_base_row, column=1).value = f"{fund['name']}近10年度收支概況彙總表"# 填入數據 (修正寫入起始欄位為 B 欄,即第 2 欄)for r_idx, rec_row in enumerate(fund['data']):for c_idx, val in enumerate(rec_row):# 這裡的 c_idx + 2 代表從 B 欄開始寫入out_ws.cell(row=current_base_row + 4 + r_idx, column=c_idx + 2).value = valcurrent_base_row += template_height# D. 換檔補白邏輯if len(file_funds_data) % 2 != 0:current_base_row += template_heightoutput_path = os.path.abspath("Final_Corrected_Report.xlsx")out_wb.save(output_path)return output_path, "已修正欄位偏移並強制恢復合併格式!"except Exception as e:return None, f"發生錯誤: {str(e)}"with gr.Blocks() as app:gr.Markdown("# 基金報表合併系統 (最終修正版)")with gr.Row():f_in = gr.File(label="上傳 Excel", file_count="multiple")h_in = gr.Number(label="設定模板高度", 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])
app.py+24-20