Spaces:
Sleeping
Sleeping
Update app.py
Browse files12343456 unmodified lines12131417151617202118192021222324232425262728293031323334323334353637383940414243444546474849505152535455563757583959606162631 unmodified line656667476869495070715253545556575859727361626364656667686970717273747576777879808182837475767778798680818283848586878889909192929394959697989910010110210393949596979899100101102103105106107108109110111112113114115116117118104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133import gradio as grimport openpyxlimport jsonimport ioimport osfrom openpyxl.utils import get_column_letterfrom openpyxl.cell.cell import MergedCell6 unmodified lines dim = sheet.column_dimensions.get(col_letter) return dim is not None and dim.hidden
def scan_excel_to_json(file_objs):def process_direct_merge(file_objs, template_height): if not file_objs: return None, "請先上傳檔案!" if not isinstance(file_objs, list): file_objs = [file_objs] # 確保 template_height 是整數 try: template_height = int(template_height) except: return None, "模板高度必須是數字!"
# 自定義排序順序 prefix_priority = {"OF-": 1, "DF-": 2, "SF-": 3, "PF-": 4} files = 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() for prefix, weight in prefix_priority.items(): if name.startswith(prefix): return (weight, name) return (99, name)
file_objs.sort(key=sort_key) grouped_results = [] files.sort(key=sort_key)
if not os.path.exists(TEMPLATE_FILE): return None, f"錯誤:找不到模板檔 {TEMPLATE_FILE}"
try: temp_wb = openpyxl.load_workbook(TEMPLATE_FILE) temp_ws = temp_wb.worksheets[0] out_wb = openpyxl.Workbook() out_ws = out_wb.active out_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].width
current_base_row = 1
for file_obj in file_objs: for file_obj in files: wb = openpyxl.load_workbook(file_obj.name, data_only=True) file_funds = [] file_funds_data = []
for sheet_name in wb.sheetnames: ws = wb[sheet_name] for row in ws.iter_rows():1 unmodified line if "彙總表" in first_val or "近10年度" in first_val: fund_name = first_val.replace("近10年度", "").replace("收支概況彙總表", "").strip() records = [] # 抓取數據 (假設標題下4列開始抓10列) # 抓取數據 (標題下 4 列開始抓 10 列) for r_idx in range(row[0].row + 4, row[0].row + 14): row_data = [ws.cell(row=r_idx, column=c).value for c in range(1, 21) if not is_hidden(ws, c) and not isinstance(ws.cell(row=r_idx, column=c), MergedCell)] 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.append({"fundName": fund_name, "records": records}) grouped_results.append({"fileName": os.path.basename(file_obj.name), "funds": file_funds})
with open("scanned_data.json", "w", encoding="utf-8") as f: json.dump(grouped_results, f, ensure_ascii=False, indent=2) return "scanned_data.json", f"已排序:{[os.path.basename(f.name) for f in file_objs]}" except Exception as e: return None, f"掃描出錯: {str(e)}" file_funds_data.append({"name": fund_name, "data": records})
def generate_combined_report(json_text): if not json_text: return None, "請輸入 JSON" try: data = json.loads(json_text) if not os.path.exists(TEMPLATE_FILE): return None, "找不到 template.xlsx" temp_wb = openpyxl.load_workbook(TEMPLATE_FILE) temp_ws = temp_wb.worksheets[0] out_wb = openpyxl.Workbook() out_ws = out_wb.active # 複製寬度 for i in range(1, 21): out_ws.column_dimensions[get_column_letter(i)].width = temp_ws.column_dimensions[get_column_letter(i)].width
curr_row = 1 h = 20 # 假設每個基金佔20列 for file_group in data: funds = file_group.get("funds", []) for fund in funds: # 複製樣式與填值 for r in range(1, h + 1): # 寫入輸出表 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=curr_row + r - 1, column=c) t_cell = out_ws.cell(row=current_base_row + r - 1, column=c) t_cell.value = s_cell.value if 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 = val out_ws.cell(row=curr_row, column=1).value = f"{fund['fundName']}近10年度收支概況彙總表" for r_idx, rec in enumerate(fund['records']): for c_idx, val in enumerate(rec): out_ws.cell(row=curr_row + 4 + r_idx, column=c_idx + 1).value = val curr_row += h # 補白邏輯:單數就跳過一格位 if len(funds) % 2 != 0: curr_row += h
out_wb.save("Final_Report.xlsx") return "Final_Report.xlsx", "生成成功!" current_base_row += template_height
# 補白邏輯:如果該檔案基金數是奇數,跳過一個高度 if len(file_funds_data) % 2 != 0: current_base_row += template_height
output_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)}"
with gr.Blocks() as app: with gr.Tab("1. 掃描"): inp = gr.File(file_count="multiple") btn = gr.Button("掃描") out_f = gr.File() out_m = gr.Textbox() btn.click(scan_excel_to_json, inp, [out_f, out_m]) with gr.Tab("2. 合併"): inp_j = gr.Textbox() btn_m = gr.Button("生成 Excel") out_ex = gr.File() btn_m.click(generate_combined_report, inp_j, [out_ex]) 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)app.py+85-73