Spaces:
Sleeping
Sleeping
Update app.py
Browse files4 unmodified lines5678910114 unmodified lines161718181920211920218 unmodified lines3031323637383940413334444535363738474849394041425143444554464748495059606162515253545556575859606162636465666768697071721 unmodified line7475767377757678798015 unmodified lines96979898991001001011021021031041051061081071081101091101111124 unmodified lines1171181191211221231241251261271201291301211221231331341351361371381391401411241251261271281291301311321331341351361371381391401411421431441451461471481491501511451521531543 unmodified lines1581591601551611621571581591631641651661671681691701711661721731681741751761721771781794 unmodified lines1841851861831871881891901 unmodified line1921931941911954 unmodified linesimport zipfileimport osfrom openpyxl.utils import get_column_letterfrom openpyxl.cell.cell import MergedCell
# 設定版型檔案名稱TEMPLATE_FILE = "template.xlsx"4 unmodified lines 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)# ==========================================8 unmodified lines 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 "" # 安全獲取第一個儲存格的值 (處理合併儲存格) first_cell = row[0] first_val = str(first_cell.value) if first_cell.value else "" # 判斷是否為標題列 if "彙總表" in first_cell_val or "近10年度" in first_cell_val: fund_name = first_cell_val.replace("近10年度", "").replace("收支概況彙總表", "").strip() # 判斷是否為標題列 (關鍵字偵測) 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{row[0].row}" fund_name = f"{sheet_name}_Row{first_cell.row}" # 抓取接下來 10 列數據 start_row_idx = row[0].row + 4 # 標題往下4列開始數據 start_row_idx = first_cell.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 # 掃描 1 到 20 欄 (確保抓到後面的累積賸餘) for c_idx in range(1, 21): # 1. 如果欄位隱藏 -> 跳過 if is_hidden(ws, c_idx): continue cell = ws.cell(row=r_idx, column=c_idx) # 2. 【關鍵修正】如果這是被合併的附屬格子 (Slave) -> 跳過 if isinstance(cell, MergedCell): continue
# 正常取值 cell_val = cell.value if cell_val is None: cell_val = "" row_data.append(cell_val) records.append(row_data) results.append({1 unmodified line "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)15 unmodified lines if not isinstance(data, list): return None, "JSON 格式錯誤:必須是列表 [...]"
# 檢查版型是否存在 if not os.path.exists(TEMPLATE_FILE): return None, f"找不到版型檔案:{TEMPLATE_FILE},請確認已上傳到 Hugging Face Files。" return None, f"找不到版型檔案:{TEMPLATE_FILE},請確認已上傳。"
# 建立 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] # 預設用第一頁 ws = wb.worksheets[0] fund_name = fund.get("fundName", "未命名") records = fund.get("records", [])4 unmodified lines # 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年 if i >= 10: break 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 data_ptr = 0 # 指向 JSON 資料的指標 # 掃描 1 到 20 欄 for c_idx in range(1, 21): # 資料填完了就停止 if data_ptr >= len(record_row): break
# 1. 檢查隱藏 if is_hidden(ws, c_idx): continue cell = ws.cell(row=current_row, column=c_idx)
# 2. 【關鍵修正】如果是合併的附屬格子 -> 跳過,不要填寫,也不要移動 data_ptr if isinstance(cell, MergedCell): continue # 3. 填入數據 val = record_row[data_ptr] cell.value = val # 移動到下一個數據 data_ptr += 1
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 檔。"3 unmodified lines
# ==========================================# Gradio 介面設定# Gradio 介面# ==========================================
with gr.Blocks(title="基金報表自動化 (Python版)") as app: gr.Markdown("# 🐍 基金報表自動化中心 (Python v1.0)")with gr.Blocks(title="基金報表自動化 (Python v2.0)") as app: gr.Markdown("# 🐍 基金報表自動化中心 (Python v2.0 - 合併儲存格修正版)") gr.Markdown("此版本已修正 A、B 欄合併導致的資料位移問題。") 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 gen_output_file = gr.File(label="下載結果", type="binary") # 按鈕動作 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)4 unmodified lines gen_btn.click(run_gen, inputs=json_input, outputs=[gen_output_file, gen_output_msg])
with gr.Tab("2. 逆向掃描 (Excel -> JSON)"): gr.Markdown("上傳 Excel,系統會自動忽略隱藏欄位,抓取所有基金資料。") gr.Markdown("上傳 Excel,系統會自動忽略隱藏欄位與合併儲存格,抓取所有基金資料。") scan_input = gr.File(label="上傳 Excel (.xlsx)") scan_btn = gr.Button("🔍 掃描並轉檔", variant="primary") scan_output_file = gr.File(label="下載 JSON")1 unmodified line
scan_btn.click(scan_excel_to_json, inputs=scan_input, outputs=[scan_output_file, scan_output_msg])
# 啟動應用app.launch()app.py+60-57