Spaces:
Sleeping
Sleeping
Update app.py
Browse files16 unmodified lines1718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990913 unmodified lines959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716815 unmodified lines18418518618718818919019119219319419516 unmodified linesreturn dim is not None and dim.hidden# ==========================================# 功能 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]# 逐列掃描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({"fundName": fund_name,"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)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:3 unmodified linesdata = json.loads(json_text)if 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", [])# 1. 修改標題ws["A1"] = f"{fund_name}近10年度收支概況彙總表"# 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 檔。"except Exception as e:return None, f"生成失敗: {str(e)}"# ==========================================# 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 壓縮包。")15 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")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()16 unmodified lines171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697983 unmodified lines10210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916015 unmodified lines17617717817918018118218318418518618718816 unmodified linesreturn dim is not None and dim.hidden# ==========================================# 功能 1: 逆向掃描 (Excel -> JSON) 【已修改支援多檔】# ==========================================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 = 0try:# 3. 最外層加入迴圈,逐一處理每個上傳的檔案for file_obj in file_objs:wb = openpyxl.load_workbook(file_obj.name, data_only=True)processed_files_count += 1for 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 + 4records = []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):continuecell = ws.cell(row=r_idx, column=c_idx)if isinstance(cell, MergedCell):continuecell_val = cell.valueif cell_val is None:cell_val = ""row_data.append(cell_val)records.append(row_data)all_results.append({"fundName": fund_name,"records": records})# 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)return output_filename, f"成功處理 {processed_files_count} 個檔案,共找到 {len(all_results)} 個基金。"except Exception as e:return None, f"發生錯誤: {str(e)}"# ==========================================# 功能 2: 生成報表 (JSON -> Excel ZIP) (維持不變)# ==========================================def generate_reports(json_text):if not json_text:3 unmodified linesdata = json.loads(json_text)if 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", [])ws["A1"] = f"{fund_name}近10年度收支概況彙總表"start_row = 5for i, record_row in enumerate(records):if i >= 10: breakcurrent_row = start_row + idata_ptr = 0for c_idx in range(1, 21):if data_ptr >= len(record_row):breakif is_hidden(ws, c_idx):continuecell = ws.cell(row=current_row, column=c_idx)if isinstance(cell, MergedCell):continueval = record_row[data_ptr]cell.value = valdata_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 檔。"except Exception as e:return None, f"生成失敗: {str(e)}"# ==========================================# 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 壓縮包。")15 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 (可多選),系統會��併所有檔案中的基金資料。")# 【關鍵修改】加入 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+70-77