Spaces:
Sleeping
Sleeping
Update app.py
Browse files43 unmodified lines44454647484950514 unmodified lines5657585960611 unmodified line63646566676869707172737475767778798081828384858687888990914 unmodified lines9697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714843 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].width4 unmodified lineswb = 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():1 unmodified lineif "彙總表" 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.value4 unmodified linest_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)43 unmodified lines44454647484950514 unmodified lines565758596061621 unmodified line646566676869707172737475767778798081828384854 unmodified lines9091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713843 unmodified linesout_ws = out_wb.activeout_ws.title = "合併報表"# 複製欄位寬度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].width4 unmodified lineswb = 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():1 unmodified lineif "彙總表" in first_val or "近10年度" in first_val:fund_name = first_val.replace("近10年度", "").replace("收支概況彙總表", "").strip()records = []# 抓取 10 年數據 (假設從標題下 4 列開始)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, 25):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.value4 unmodified linest_cell.alignment = copy(s_cell.alignment)t_cell.number_format = copy(s_cell.number_format)# B. 安全複製合併儲存格 (修正錯誤點)if hasattr(temp_ws, "merged_cells"):for merged_range in list(temp_ws.merged_cells.ranges):# 確保合併範圍在當前模板高度內才處理if merged_range.min_row <= template_height:try:# 建立偏移後的範圍new_range = merged_range.shift(row_shift=current_base_row - 1)if new_range and hasattr(new_range, 'coord'):if new_range.coord not in out_ws.merged_cells:out_ws.merge_cells(new_range.coord)except Exception:continue # 忽略無法偏移的範圍# C. 填入資料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, "合併成功!"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])if __name__ == "__main__":app.launch(server_name="0.0.0.0", server_port=7860)
app.py+37-47