Spaces:
Sleeping
Sleeping
Update app.py
Browse files8 unmodified lines910111213141213141516171819182021222223242526272829232425313233262728293637303132393341423435363738394849404142535455434445584660616263646566474849505168527071727374535476775556798081575883596085868761899091626393949596646566676899697010210310471727310610710874751101111127677781147980811171188283841201211221231241251261271281291301318586878889909113313413513613713813914014192939495969798991431441001011461471481021031041501051061071081091101111121131141151161171181191521201218 unmodified lines
TEMPLATE_FILE = "template.xlsx"
# ==========================================# 功能 1: 逆向掃描 (含特定前綴排序邏輯)# ==========================================def is_hidden(sheet, col_idx): col_letter = get_column_letter(col_idx) dim = sheet.column_dimensions.get(col_letter) return dim is not None and dim.hidden
def scan_excel_to_json(file_objs): if not file_objs: return None, "請先上傳檔案!" if not isinstance(file_objs, list): file_objs = [file_objs]
# --- 自定義排序權重 --- # 順序:OF- > DF- > SF- > PF- prefix_priority = { "OF-": 1, "DF-": 2, "SF-": 3, "PF-": 4 } # 自定義排序順序 prefix_priority = {"OF-": 1, "DF-": 2, "SF-": 3, "PF-": 4}
def sort_key(file_obj): name = os.path.basename(file_obj.name).upper() # 轉大寫比對 # 尋找檔名是否以指定的 prefix 開頭 def sort_key(f): name = os.path.basename(f.name).upper() for prefix, weight in prefix_priority.items(): if name.startswith(prefix): return (weight, name) # 返回 (權重, 檔名) 的元組進行排序 return (99, name) # 若無匹配,排在最後 return (weight, name) return (99, name)
# 執行排序 file_objs.sort(key=sort_key) grouped_results = [] grouped_results = [] try: for file_obj in file_objs: wb = openpyxl.load_workbook(file_obj.name, data_only=True) 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 "" first_val = str(row[0].value) if row[0].value else "" if "彙總表" in first_val or "近10年度" in first_val: fund_name = first_val.replace("近10年度", "").replace("收支概況彙總表", "").strip() start_row_idx = first_cell.row + 4 records = [] for r_idx in range(start_row_idx, start_row_idx + 10): row_data = [] for c_idx in range(1, 21): if is_hidden(ws, c_idx): continue cell = ws.cell(row=r_idx, column=c_idx) if isinstance(cell, MergedCell): continue row_data.append(cell.value if cell.value is not None else "") # 抓取數據 (假設標題下4列開始抓10列) for r_idx in range(row[0].row + 4, row[0].row + 14): row_data = [ws.cell(row=r_idx, column=c).value for c in range(1, 21) if not is_hidden(ws, c) and not isinstance(ws.cell(row=r_idx, column=c), MergedCell)] records.append(row_data) file_funds.append({"fundName": fund_name, "records": records}) grouped_results.append({ "fileName": file_display_name, "funds": file_funds }) grouped_results.append({"fileName": os.path.basename(file_obj.name), "funds": file_funds})
output_filename = "scanned_data.json" with open(output_filename, "w", encoding="utf-8") as f: with open("scanned_data.json", "w", encoding="utf-8") as f: json.dump(grouped_results, f, ensure_ascii=False, indent=2) sorted_names = [os.path.basename(f.name) for f in file_objs] return output_filename, f"排序完成:{ ' > '.join(sorted_names) }" return "scanned_data.json", f"已排序:{[os.path.basename(f.name) for f in file_objs]}" except Exception as e: return None, f"掃描失敗: {str(e)}" return None, f"掃描出錯: {str(e)}"
# ==========================================# 功能 2: 生成合併報表 (保持補白邏輯)# ==========================================def generate_combined_report(json_text): if not json_text: return None, "請輸入 JSON 資料" if not json_text: return None, "請輸入 JSON" try: grouped_data = json.loads(json_text) if not os.path.exists(TEMPLATE_FILE): return None, f"找不到 {TEMPLATE_FILE}"
data = json.loads(json_text) if not os.path.exists(TEMPLATE_FILE): return None, "找不到 template.xlsx" 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 out_ws.column_dimensions[get_column_letter(i)].width = temp_ws.column_dimensions[get_column_letter(i)].width
current_base_row = 1 # 請務必確認模板一個基金佔用的總列數(含間距) template_height = 20 curr_row = 1 h = 20 # 假設每個基金佔20列 for file_group in grouped_data: for file_group in data: funds = file_group.get("funds", []) for fund in funds: # 複製樣式與內容 for r in range(1, template_height + 1): # 複製樣式與填值 for r in range(1, h + 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年度收支概況彙總表" s_cell = temp_ws.cell(row=r, column=c) t_cell = out_ws.cell(row=curr_row + r - 1, column=c) t_cell.value = s_cell.value if s_cell.has_style: t_cell.font, t_cell.border = copy(s_cell.font), copy(s_cell.border) t_cell.fill, t_cell.alignment = copy(s_cell.fill), copy(s_cell.alignment) # 填入資料 (假設從第 5 列開始) records = fund.get("records", []) 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 current_base_row += template_height
# --- 補白邏輯:如果檔案基金數是奇數,多跳一個位子 --- out_ws.cell(row=curr_row, column=1).value = f"{fund['fundName']}近10年度收支概況彙總表" for r_idx, rec in enumerate(fund['records']): for c_idx, val in enumerate(rec): out_ws.cell(row=curr_row + 4 + r_idx, column=c_idx + 1).value = val curr_row += h # 補白邏輯:單數就跳過一格位 if len(funds) % 2 != 0: # 這裡不複製內容,直接增加 Row 座標,達到留下空白的效果 current_base_row += template_height curr_row += h
output_path = "Final_Merged_Report.xlsx" out_wb.save(output_path) return output_path, "報表合併完成!已套用特定前綴排序。" out_wb.save("Final_Report.xlsx") return "Final_Report.xlsx", "生成成功!" except Exception as e: return None, f"生成失敗: {str(e)}" return None, f"錯誤: {str(e)}"
with gr.Blocks() as app: with gr.Tab("1. 掃描"): inp = gr.File(file_count="multiple") btn = gr.Button("掃描") out_f = gr.File() out_m = gr.Textbox() btn.click(scan_excel_to_json, inp, [out_f, out_m]) with gr.Tab("2. 合併"): inp_j = gr.Textbox() btn_m = gr.Button("生成 Excel") out_ex = gr.File() btn_m.click(generate_combined_report, inp_j, [out_ex])
# Gradio 介面保持與之前相同if __name__ == "__main__": app.launch(server_name="0.0.0.0", server_port=7860)app.py+65-96