Spaces:
Sleeping
Sleeping
Update app.py
Browse files5 unmodified lines6789101112131415161716 unmodified lines34353631373839403 unmodified lines44454641474849501 unmodified line525354555657583 unmodified lines6263645859656667626364656667686970717273747576777879808172828384857677787980868788828984858687909192939094959697989596979899100101102103104105106107991001011021031041051061081091101071121131141151161171081091101111121131141211151161171181251261271281191201211221231241251331261271281361371291301311321335 unmodified lines
TEMPLATE_FILE = "template.xlsx"
def is_hidden(sheet, col_idx): """檢查 Excel 欄位是否隱藏""" col_letter = get_column_letter(col_idx) dim = sheet.column_dimensions.get(col_letter) return dim is not None and dim.hidden
def process_direct_merge(file_objs, template_height): if not file_objs: return None, "請先上傳檔案!"16 unmodified lines files.sort(key=sort_key)
if not os.path.exists(TEMPLATE_FILE): return None, f"找不到模板檔案 {TEMPLATE_FILE}" return None, f"找不到模板檔案:{TEMPLATE_FILE}"
try: temp_wb = openpyxl.load_workbook(TEMPLATE_FILE)3 unmodified lines out_ws = out_wb.active out_ws.title = "合併報表"
# 複製全域列寬 # A. 複製全域欄位寬度 for i in range(1, 26): col_l = get_column_letter(i) if col_l in temp_ws.column_dimensions:1 unmodified line
current_base_row = 1
# 2. 逐一處理檔案 for file_obj in files: wb = openpyxl.load_workbook(file_obj.name, data_only=True) file_funds_data = []3 unmodified lines for 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() fund_name = first_val.replace("近10年度", "").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)] # --- 核心修正:抓取數據 (精確對應欄位座標) --- # 依照您的原始邏輯,從標題列下方第 4 列開始抓 start_row = row[0].row + 4 for r_idx in range(start_row, start_row + 10): row_data = [] # 嚴格抓取 1 到 20 欄,不跳過合併格,確保陣列長度永遠是 20 for c_idx in range(1, 21): cell_val = ws.cell(row=r_idx, column=c_idx).value row_data.append(cell_val if cell_val is not None else "") records.append(row_data) file_funds_data.append({"name": fund_name, "data": records})
# 3. 寫入新工作表 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 - 1 t_cell = out_ws.cell(row=t_row, column=c) # 除了數據填入區,其餘複製模板內容 (標題、備註等) if not (5 <= r <= 14): t_cell = out_ws.cell(row=current_base_row + r - 1, 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.font, t_cell.border = copy(s_cell.font), copy(s_cell.border) t_cell.fill, t_cell.alignment = copy(s_cell.fill), 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.bounds new_start_row = current_base_row + min_row - 1 new_end_row = current_base_row + max_row - 1 try: # 先解除可能存在的衝突合併,再重新合併 out_ws.merge_cells( start_row=new_start_row, start_column=min_col, end_row=new_end_row, end_column=max_col ) except: pass out_ws.merge_cells( start_row=current_base_row + min_row - 1, start_column=min_col, end_row=current_base_row + max_row - 1, end_column=max_col )
# 填入標題與數據
# 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 = val for r_idx, row_vals in enumerate(fund['data']): for c_idx, val in enumerate(row_vals): # 寫入位置對應抓取位置 (1-20欄) out_ws.cell(row=current_base_row + 4 + r_idx, column=c_idx + 1).value = val current_base_row += template_height
# D. 換檔補白邏輯 # 補白邏輯 if len(file_funds_data) % 2 != 0: current_base_row += template_height
output_path = os.path.abspath("Final_Corrected_Report.xlsx") out_wb.save(output_path) return output_path, "已修正欄位偏移並強制恢復合併格式!"
out_path = os.path.abspath("Final_Combined_Report.xlsx") out_wb.save(out_path) return out_path, f"合併完成!已修正欄位偏移問題。" except Exception as e: return None, f"發生錯誤: {str(e)}"
with gr.Blocks() as app: gr.Markdown("# 基金報表合併系統 (最終修正版)") 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") 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+45-52