Spaces:
Sleeping
Sleeping
Update app.py
Browse files4 unmodified lines56789104 unmodified lines151617181920212223248 unmodified lines3334353637383940414243444546474849505152535455565758596061626364656667681 unmodified line7071727374757677787915 unmodified lines95969798991001011021031041051061071081091101111121134 unmodified lines1181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471483 unmodified lines1521531541551561571581591601611621631641651661671681691701711721731741754 unmodified lines1801811821831841851861 unmodified line1881891901911924 unmodified linesimport zipfileimport osfrom openpyxl.utils import get_column_letter# 設定版型檔案名稱TEMPLATE_FILE = "template.xlsx"4 unmodified linesdim = sheet.column_dimensions.get(col_letter)return dim is not None and dim.hiddendef get_visible_cell_value(cell):"""讀取儲存格的值,如果是合併儲存格則嘗試讀取"""return cell.value# ==========================================# 功能 1: 逆向掃描 (Excel -> JSON)# ==========================================8 unmodified linesfor 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# 處理 Noneif 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 linesif 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", [])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年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# 為了不用存到硬碟,我們存到 BytesIOexcel_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 介面設定# ==========================================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)4 unmodified linesgen_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")1 unmodified linescan_btn.click(scan_excel_to_json, inputs=scan_input, outputs=[scan_output_file, scan_output_msg])# 啟動應用app.launch()4 unmodified lines5678910114 unmodified lines1617181920218 unmodified lines303132333435363738394041424344454647484950515253545556575859606162636465666768697071721 unmodified line7475767778798015 unmodified lines969798991001011021031041051061071081091101111124 unmodified lines1171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531543 unmodified lines1581591601611621631641651661671681691701711721731741751761771781794 unmodified lines1841851861871881891901 unmodified line1921931941954 unmodified linesimport zipfileimport osfrom openpyxl.utils import get_column_letterfrom openpyxl.cell.cell import MergedCell# 設定版型檔案名稱TEMPLATE_FILE = "template.xlsx"4 unmodified linesdim = sheet.column_dimensions.get(col_letter)return dim is not None and dim.hidden# ==========================================# 功能 1: 逆向掃描 (Excel -> JSON)# ==========================================8 unmodified linesfor 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 # 標題往下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):# 1. 如果欄位隱藏 -> 跳過if is_hidden(ws, c_idx):continuecell = ws.cell(row=r_idx, column=c_idx)# 2. 【關鍵修正】如果這是被合併的附屬格子 (Slave) -> 跳過if isinstance(cell, MergedCell):continue# 正常取值cell_val = cell.valueif cell_val is None:cell_val = ""row_data.append(cell_val)records.append(row_data)results.append({1 unmodified line"records": records})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 linesif not isinstance(data, list):return None, "JSON 格式錯誤:必須是列表 [...]"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]fund_name = fund.get("fundName", "未命名")records = fund.get("records", [])4 unmodified lines# 2. 寫入數據start_row = 5for i, record_row in enumerate(records):if i >= 10: breakcurrent_row = start_row + idata_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):continuecell = ws.cell(row=current_row, column=c_idx)# 2. 【關鍵修正】如果是合併的附屬格子 -> 跳過,不要填寫,也不要移動 data_ptrif isinstance(cell, MergedCell):continue# 3. 填入數據val = record_row[data_ptr]cell.value = val# 移動到下一個數據data_ptr += 1excel_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 介面# ==========================================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")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)4 unmodified linesgen_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")1 unmodified linescan_btn.click(scan_excel_to_json, inputs=scan_input, outputs=[scan_output_file, scan_output_msg])app.launch()
app.py+60-57