Spaces:
Sleeping
Sleeping
Update app.py
Browse files15 unmodified lines161718192021229 unmodified lines323334353637387 unmodified lines464748495051525311 unmodified lines656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213315 unmodified linesif not file_objs:return None, "請先上傳檔案!"# 確保 template_height 是整數try:template_height = int(template_height)except:9 unmodified linesif name.startswith(prefix):return (weight, name)return (99, name)files.sort(key=sort_key)if not os.path.exists(TEMPLATE_FILE):7 unmodified linesout_ws = out_wb.activeout_ws.title = "合併報表"# 複製欄位寬度for i in range(1, 21):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].width11 unmodified linesif "彙總表" in first_val or "近10年度" in first_val:fund_name = first_val.replace("近10年度", "").replace("收支概況彙總表", "").strip()records = []# 抓取數據 (標題下 4 列開始抓 10 列)for r_idx in range(row[0].row + 4, row[0].row + 14):row_data = [ws.cell(row=r_idx, column=c_idx).value if not is_hidden(ws, c_idx) and not isinstance(ws.cell(row=r_idx, column=c_idx), MergedCell) else "" for c_idx in range(1, 21)]records.append(row_data)file_funds_data.append({"name": fund_name, "data": records})# 寫入輸出表for fund in file_funds_data:# 複製樣式與結構for r in range(1, template_height + 1):for c in range(1, 21):s_cell = temp_ws.cell(row=r, column=c)t_cell = out_ws.cell(row=current_base_row + r - 1, column=c)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)# 填入內容out_ws.cell(row=current_base_row, column=1).value = f"{fund['name']}近10年度收支概況彙總表"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, f"成功!共合併 {len(files)} 個檔案,已套用自定義高度 {template_height}。"except Exception as e:return None, f"處理過程發生錯誤: {str(e)}"# ==========================================# Gradio 介面佈局# ==========================================with gr.Blocks(title="基金報表快速合併工具 v2.5") as app:gr.Markdown("# 📊 基金報表一鍵合併系統 (自定義高度版)")with gr.Row():with gr.Column(scale=2):file_input = gr.File(label="1. 上傳原始檔案 (可選多個)", file_count="multiple")with gr.Column(scale=1):height_input = gr.Number(label="2. 設定模板高度 (列數)", value=20, precision=0)gr.Markdown("> **提示:** 這是指 `template.xlsx` 中一個基金區域所佔的總列數(包含下方的空白間隔)。")merge_btn = gr.Button("🚀 3. 開始直接合併", variant="primary")gr.HTML("<hr>")with gr.Row():output_file = gr.File(label="4. 下載最終報表")status_msg = gr.Textbox(label="處理狀態", interactive=False)merge_btn.click(fn=process_direct_merge,inputs=[file_input, height_input],outputs=[output_file, status_msg])if __name__ == "__main__":app.launch(server_name="0.0.0.0", server_port=7860)15 unmodified lines1617181920219 unmodified lines3132333435367 unmodified lines444546474849505111 unmodified lines6364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714815 unmodified linesif not file_objs:return None, "請先上傳檔案!"try:template_height = int(template_height)except:9 unmodified linesif name.startswith(prefix):return (weight, name)return (99, name)files.sort(key=sort_key)if not os.path.exists(TEMPLATE_FILE):7 unmodified linesout_ws = out_wb.activeout_ws.title = "合併報表"# 複製全域欄位寬度for i in range(1, 30): # 掃描到第 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].width11 unmodified linesif "彙總表" in first_val or "近10年度" in first_val:fund_name = first_val.replace("近10年度", "").replace("收支概況彙總表", "").strip()records = []# 依照截圖,數據區在標題下 4 列 (第 5 列到 14 列)for r_offset in range(4, 14):r_idx = row[0].row + r_offsetrow_data = []# 讀取對應模板的數據欄位 (假設 1 到 20 欄)for c_idx in range(1, 21):if is_hidden(ws, c_idx): continuecell = ws.cell(row=r_idx, column=c_idx)# 即使是合併儲存格,data_only 模式下左上角也會有值row_data.append(cell.value if cell.value is not None else "")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, 25): # 增加掃描寬度s_cell = temp_ws.cell(row=r, column=c)t_cell = out_ws.cell(row=current_base_row + r - 1, column=c)# 只有非數據填入區才複製模板文字 (避免覆蓋掉新數據)# 假設數據區在模板第 5-14 列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)# B. 處理合併儲存格的複製for merged_range in temp_ws.merged_cells.ranges:# 計算在新表中的相對位置new_range = merged_range.shift(row_shift=current_base_row - 1)# 檢查是否已經合併過,避免重複合併報錯if new_range.coord not in out_ws.merged_cells:out_ws.merge_cells(new_range.coord)# C. 填入正確的基金名稱 (A1)out_ws.cell(row=current_base_row, column=1).value = f"{fund['name']}近10年度收支概況彙總表"# D. 填入數據 (從第 5 列開始)for r_idx, rec_row in enumerate(fund['data']):data_ptr = 0for c_idx in range(1, 21):if is_hidden(temp_ws, c_idx): continuetarget_cell = out_ws.cell(row=current_base_row + 4 + r_idx, column=c_idx)if isinstance(target_cell, MergedCell): continueif data_ptr < len(rec_row):target_cell.value = rec_row[data_ptr]data_ptr += 1current_base_row += template_height# 補白邏輯if len(file_funds_data) % 2 != 0:current_base_row += template_heightoutput_path = os.path.abspath("Fixed_Format_Report.xlsx")out_wb.save(output_path)return output_path, f"成功!請檢查格式。建議高度設定為 20 以上。"except Exception as e:return None, f"發生錯誤: {str(e)}"# Gradio 介面部分與前次相同with gr.Blocks(title="基金報表修復版") as app:gr.Markdown("# 📊 基金報表合併 (修復合併儲存格與備註)")with gr.Row():file_input = gr.File(label="上傳原始檔案", file_count="multiple")height_input = gr.Number(label="設定模板高度 (請參考 Excel 總列數)", value=20, precision=0)merge_btn = gr.Button("🚀 開始合併並修復格式", variant="primary")output_file = gr.File(label="下載結果")status_msg = gr.Textbox(label="狀態")merge_btn.click(fn=process_direct_merge, inputs=[file_input, height_input], outputs=[output_file, status_msg])if __name__ == "__main__":app.launch(server_name="0.0.0.0", server_port=7860)
app.py+58-43