Spaces:
Sleeping
Sleeping
Update app.py
Browse files5 unmodified lines6789101112131415161726 unmodified lines444546474849501 unmodified line525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596975 unmodified lines1031041051061071081091101111121131141151161171181191201211221231241251261271281295 unmodified linesTEMPLATE_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.hiddendef process_direct_merge(file_objs, template_height):if not file_objs:return None, "請先上傳檔案!"26 unmodified linesout_ws = out_wb.activeout_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 linecurrent_base_row = 1# 2. 逐一處理檔案for file_obj in files:wb = openpyxl.load_workbook(file_obj.name, data_only=True)file_funds_data = []for sheet_name in wb.sheetnames:ws = wb[sheet_name]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("收支概況彙總表", "").strip()records = []# --- 核心修正:抓取數據 (精確對應欄位座標) ---# 依照您的原始邏輯,從標題列下方第 4 列開始抓start_row = row[0].row + 4for r_idx in range(start_row, start_row + 10):row_data = []# 嚴格抓取 1 到 20 欄,不跳過合併格,確保陣列長度永遠是 20for c_idx in range(1, 21):cell_val = ws.cell(row=r_idx, column=c_idx).valuerow_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:# 複製樣式與合併格for r in range(1, template_height + 1):for c in range(1, 26):s_cell = temp_ws.cell(row=r, column=c)t_cell = out_ws.cell(row=current_base_row + r - 1, column=c)if not (5 <= r <= 14): # 非數據區複製模板文字t_cell.value = s_cell.valueif s_cell.has_style: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)# 套用合併儲存格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-20欄)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_heightout_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("# 基金報表一鍵合併 (修正欄位偏移版)")with gr.Row():f_in = gr.File(label="上傳 Excel", file_count="multiple")h_in = gr.Number(label="模板高度", value=20)5 unmodified lines6789101126 unmodified lines383940414243441 unmodified line4647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991005 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271281291301311325 unmodified linesTEMPLATE_FILE = "template.xlsx"def process_direct_merge(file_objs, template_height):if not file_objs:return None, "請先上傳檔案!"26 unmodified linesout_ws = out_wb.activeout_ws.title = "合併報表"# 複製全域列寬for i in range(1, 26):col_l = get_column_letter(i)if col_l in temp_ws.column_dimensions:1 unmodified linecurrent_base_row = 1for file_obj in files:# 使用 data_only=True 讀取數值wb = openpyxl.load_workbook(file_obj.name, data_only=True)file_funds_data = []for sheet_name in wb.sheetnames:ws = wb[sheet_name]for row in ws.iter_rows():# 即使 A、B 合併,first_val 通常在第一格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("收支概況彙總表", "").strip()records = []start_row_idx = row[0].row + 4for r_idx in range(start_row_idx, start_row_idx + 10):# --- 核心修正:處理 AB 欄合併導致的偏移 ---# 如果原始檔 AB 欄合併,資料在 A,則 B 欄為空。# 我們要抓取原始檔的 A, C, D, E... 欄來對應模板的 B, C, D, E... 欄。# 1. 抓取原始檔的第一個值 (A 欄,通常是年度)year_val = ws.cell(row=r_idx, column=1).value# 2. 抓取剩餘資料 (跳過原始檔 B 欄,從 C 欄即第 3 欄開始抓)# 這樣可以確保「業務總收入」能正確對位other_data = [ws.cell(row=r_idx, column=c).value for c in range(3, 22)]# 組合後的資料:[年度, 業務總收入, 業務總支出, ...]combined_row = [year_val] + other_datarecords.append(combined_row)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_cell = out_ws.cell(row=current_base_row + r - 1, column=c)if not (5 <= r <= 14):t_cell.value = s_cell.valueif s_cell.has_style: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)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)# B. 填入數據 (從模板的 B 欄,即第 2 欄開始填寫年度)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):# 寫入位置:模板的 B 欄是第 2 欄out_ws.cell(row=current_base_row + 4 + r_idx, column=c_idx + 2).value = valcurrent_base_row += template_heightif len(file_funds_data) % 2 != 0:current_base_row += template_heightout_path = os.path.abspath("Final_Combined_Report.xlsx")out_wb.save(out_path)return out_path, "已修正 AB 欄合併導致的資料偏移問題!"except Exception as e:return None, f"發生錯誤: {str(e)}"# Gradio UI 保持不變with gr.Blocks() as app:gr.Markdown("# 基金報表合併系統 (AB 欄合併修正版)")with gr.Row():f_in = gr.File(label="上傳 Excel", file_count="multiple")h_in = gr.Number(label="模板高度", value=20)
app.py+31-28