Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line234556789101011131415161718122013141523161718271920213132332223242526272829303132333435363738394041424344354546384748495051424352455354554956575253545558595860616162636465636467686970717273747565666768697078798081717273747583847677877879899080818292838485958687978889909192102103104105106107939495961091101111121131149798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321161331341181191351361371381211221231241251261271281291301311321331341351361371381391401391401421431441451461471411421431441451461471481491501511521531521541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881 unmodified lineimport openpyxlimport jsonimport ioimport zipfileimport osfrom openpyxl.utils import get_column_letterfrom openpyxl.cell.cell import MergedCellfrom copy import copy
# 設定版型檔案名稱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
# ==========================================# 功能 1: 逆向掃描 (Excel -> JSON) 【已修改支援多檔】# 功能 1: 逆向掃描 (含特定前綴排序邏輯)# ==========================================def scan_excel_to_json(file_objs): # 1. 檢查是否有檔案 if not file_objs: return None, "請先上傳檔案!" # 2. 確保輸入是列表 (處理單檔或多檔的情況) if not isinstance(file_objs, list): file_objs = [file_objs]
all_results = [] # 用來儲存所有檔案的結果 processed_files_count = 0
# --- 自定義排序權重 --- # 順序:OF- > DF- > SF- > PF- prefix_priority = { "OF-": 1, "DF-": 2, "SF-": 3, "PF-": 4 }
def sort_key(file_obj): name = os.path.basename(file_obj.name).upper() # 轉大寫比對 # 尋找檔名是否以指定的 prefix 開頭 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 = [] try: # 3. 最外層加入迴圈,逐一處理每個上傳的檔案 for file_obj in file_objs: wb = openpyxl.load_workbook(file_obj.name, data_only=True) processed_files_count += 1 file_funds = [] file_display_name = os.path.basename(file_obj.name) for sheet_name in wb.sheetnames: ws = wb[sheet_name] # 逐列掃描 for row in ws.iter_rows(): # 安全獲取第一個儲存格的值 first_cell = row[0] first_val = str(first_cell.value) if first_cell.value else "" # 判斷是否為標題列 if "彙總表" in first_val or "近10年度" in first_val: fund_name = first_val.replace("近10年度", "").replace("收支概況彙總表", "").strip() if not fund_name: fund_name = f"{sheet_name}_Row{first_cell.row}" # 抓取接下來 10 列數據 start_row_idx = first_cell.row + 4 records = [] for r_idx in range(start_row_idx, start_row_idx + 10): row_data = [] # 掃描 1 到 20 欄 for c_idx in range(1, 21): if is_hidden(ws, c_idx): continue if is_hidden(ws, c_idx): continue cell = ws.cell(row=r_idx, column=c_idx) if isinstance(cell, MergedCell): continue cell_val = cell.value if cell_val is None: cell_val = "" row_data.append(cell_val) if isinstance(cell, MergedCell): continue row_data.append(cell.value if cell.value is not None else "") records.append(row_data) file_funds.append({"fundName": fund_name, "records": records}) all_results.append({ "fundName": fund_name, "records": records }) grouped_results.append({ "fileName": file_display_name, "funds": file_funds })
# 4. 輸出結果 json_output = json.dumps(all_results, ensure_ascii=False, indent=2) output_filename = "scanned_data.json" with open(output_filename, "w", encoding="utf-8") as f: f.write(json_output) json.dump(grouped_results, f, ensure_ascii=False, indent=2) return output_filename, f"成功處理 {processed_files_count} 個檔案,共找到 {len(all_results)} 個基金。"
sorted_names = [os.path.basename(f.name) for f in file_objs] return output_filename, f"排序完成:{ ' > '.join(sorted_names) }" except Exception as e: return None, f"發生錯誤: {str(e)}" return None, f"掃描失敗: {str(e)}"
# ==========================================# 功能 2: 生成報表 (JSON -> Excel ZIP) (維持不變)# 功能 2: 生成合併報表 (保持補白邏輯)# ==========================================def generate_reports(json_text):def generate_combined_report(json_text): if not json_text: return None, "請輸入 JSON 資料" try: data = json.loads(json_text) if not isinstance(data, list): return None, "JSON 格式錯誤:必須是列表 [...]" if not os.path.exists(TEMPLATE_FILE): return None, f"找不到版型檔案:{TEMPLATE_FILE},請確認已上傳。" grouped_data = json.loads(json_text) if not os.path.exists(TEMPLATE_FILE): return None, f"找不到 {TEMPLATE_FILE}"
zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED, False) as zip_file: for fund in data: wb = openpyxl.load_workbook(TEMPLATE_FILE) ws = wb.worksheets[0] 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 = "合併報表"
# 1. 複製欄位寬度 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 # 請務必確認模板一個基金佔用的總列數(含間距) template_height = 20 for file_group in grouped_data: funds = file_group.get("funds", []) for fund in funds: # 複製樣式與內容 for r in range(1, template_height + 1): for c in range(1, 21): source_cell = temp_ws.cell(row=r, column=c) target_cell = out_ws.cell(row=current_base_row + r - 1, column=c) target_cell.value = source_cell.value if source_cell.has_style: target_cell.font = copy(source_cell.font) target_cell.border = copy(source_cell.border) target_cell.fill = copy(source_cell.fill) target_cell.alignment = copy(source_cell.alignment) target_cell.number_format = copy(source_cell.number_format)
# 填入標題 out_ws.cell(row=current_base_row, column=1).value = f"{fund['fundName']}近10年度收支概況彙總表" fund_name = fund.get("fundName", "未命名") # 填入資料 (假設從第 5 列開始) records = fund.get("records", [])
ws["A1"] = f"{fund_name}近10年度收支概況彙總表" for r_idx, record_row in enumerate(records): for c_idx, val in enumerate(record_row): out_ws.cell(row=current_base_row + 4 + r_idx, column=c_idx + 1).value = val start_row = 5 for i, record_row in enumerate(records): if i >= 10: break current_row = start_row + i data_ptr = 0 for c_idx in range(1, 21): if data_ptr >= len(record_row): break if is_hidden(ws, c_idx): continue cell = ws.cell(row=current_row, column=c_idx) if isinstance(cell, MergedCell): continue val = record_row[data_ptr] cell.value = val data_ptr += 1 current_base_row += template_height
excel_buffer = io.BytesIO() wb.save(excel_buffer) excel_buffer.seek(0) zip_file.writestr(f"{fund_name}.xlsx", excel_buffer.read()) return zip_buffer.getvalue(), "生成成功!請下載 ZIP 檔。" # --- 補白邏輯:如果檔案基金數是奇數,多跳一個位子 --- if len(funds) % 2 != 0: # 這裡不複製內容,直接增加 Row 座標,達到留下空白的效果 current_base_row += template_height
output_path = "Final_Merged_Report.xlsx" out_wb.save(output_path) return output_path, "報表合併完成!已套用特定前綴排序。" except Exception as e: return None, f"生成失敗: {str(e)}"
# ==========================================# Gradio 介面# Gradio 介面保持與之前相同# ==========================================with gr.Blocks(title="基金報表自動化 (Python v2.1)") as app: gr.Markdown("# 🐍 基金報表自動化中心 (Python v2.1 - 支援多檔上傳)") gr.Markdown("此版本已修正 A、B 欄合併問題,並支援一次上傳多個 Excel 進行逆向掃描。") with gr.Tab("1. 生成報表 (JSON -> Excel)"): gr.Markdown("貼上 JSON 資料,系統將自動生成 ZIP 壓縮包。") json_input = gr.Textbox(lines=15, label="輸入 JSON", placeholder='[{"fundName": "範例", "records": [[114, 5000...]]}]') gen_btn = gr.Button("🚀 生成 ZIP", variant="primary") gen_output_msg = gr.Textbox(label="狀態") gen_output_file = gr.File(label="下載結果", type="binary") def run_gen(text): zip_data, msg = generate_reports(text) if zip_data: out_path = "reports.zip" with open(out_path, "wb") as f: f.write(zip_data) return out_path, msg else: return None, msg
gen_btn.click(run_gen, inputs=json_input, outputs=[gen_output_file, gen_output_msg])
with gr.Tab("2. 逆向掃描 (Excel -> JSON)"): gr.Markdown("上傳 Excel (可多選),系統會合併所有檔案中的基金資料。") # 【關鍵修改】加入 file_count="multiple" scan_input = gr.File(label="上傳 Excel (.xlsx)", file_count="multiple") scan_btn = gr.Button("🔍 掃描並轉檔", variant="primary") scan_output_file = gr.File(label="下載 JSON") scan_output_msg = gr.Textbox(label="狀態") scan_btn.click(scan_excel_to_json, inputs=scan_input, outputs=[scan_output_file, scan_output_msg])
app.launch()app.py+92-128