Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192import gradio as grimport openpyxlimport jsonimport ioimport zipfileimport osfrom openpyxl.utils import get_column_letter
# 設定版型檔案名稱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
def get_visible_cell_value(cell): """讀取儲存格的值,如果是合併儲存格則嘗試讀取""" return cell.value
# ==========================================# 功能 1: 逆向掃描 (Excel -> JSON)# ==========================================def scan_excel_to_json(file_obj): if file_obj is None: return None, "請先上傳檔案!" try: wb = openpyxl.load_workbook(file_obj.name, data_only=True) results = []
for sheet_name in wb.sheetnames: ws = wb[sheet_name] # 預先判斷哪些欄位是隱藏的 (掃描到 R 欄/第18欄) visible_cols = [] for c in range(1, 19): if not is_hidden(ws, c): visible_cols.append(c)
# 逐列掃描 for row in ws.iter_rows(): # 安全獲取第一個儲存格的值 first_cell_val = str(row[0].value) if row[0].value else "" # 判斷是否為標題列 if "彙總表" in first_cell_val or "近10年度" in first_cell_val: fund_name = first_cell_val.replace("近10年度", "").replace("收支概況彙總表", "").strip() if not fund_name: fund_name = f"{sheet_name}_Row{row[0].row}" # 抓取接下來 10 列數據 start_row_idx = row[0].row + 4 # 標題往下4列開始數據 records = [] for r_idx in range(start_row_idx, start_row_idx + 10): row_data = [] # 只讀取「可見」的欄位 for c_idx in visible_cols: cell_val = ws.cell(row=r_idx, column=c_idx).value # 處理 None if cell_val is None: cell_val = "" row_data.append(cell_val) records.append(row_data) results.append({ "fundName": fund_name, "records": records })
# 轉成 JSON 字串 json_output = json.dumps(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) return output_filename, f"成功掃描!共找到 {len(results)} 個基金。"
except Exception as e: return None, f"發生錯誤: {str(e)}"
# ==========================================# 功能 2: 生成報表 (JSON -> Excel ZIP)# ==========================================def generate_reports(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},請確認已上傳到 Hugging Face Files。"
# 建立 ZIP 緩衝區 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] # 預設用第一頁 fund_name = fund.get("fundName", "未命名") records = fund.get("records", [])
# 1. 修改標題 ws["A1"] = f"{fund_name}近10年度收支概況彙總表"
# 2. 寫入數據 start_row = 5 # 判斷可見欄位 (邏輯與讀取時相同,確保寫入位置正確) # 也就是 JSON 的第 1 個數寫入 A,第 2 個數寫入 C (跳過B)... visible_cols = [] for c in range(1, 19): if not is_hidden(ws, c): visible_cols.append(c)
for i, record_row in enumerate(records): if i >= 10: break # 最多10年 current_row = start_row + i # 依序填入可見欄位 for data_idx, val in enumerate(record_row): if data_idx < len(visible_cols): target_col = visible_cols[data_idx] # 寫入儲存格 ws.cell(row=current_row, column=target_col).value = val
# 3. 存檔並加入 ZIP # 為了不用存到硬碟,我們存到 BytesIO 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 檔。"
except Exception as e: return None, f"生成失敗: {str(e)}"
# ==========================================# Gradio 介面設定# ==========================================
with gr.Blocks(title="基金報表自動化 (Python版)") as app: gr.Markdown("# 🐍 基金報表自動化中心 (Python v1.0)") 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") # binary for zip download # 按鈕動作 def run_gen(text): zip_data, msg = generate_reports(text) if zip_data: # 寫入暫存檔以便 Gradio 下載 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,系統會自動忽略隱藏欄位,抓取所有基金資料。") scan_input = gr.File(label="上傳 Excel (.xlsx)") 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.pyAdded+192