""" backend/edkb_system/skills/excel_bridge.py 用途:Windows 环境下通过 Excel COM 将 .xls 转为 .xlsx。 依赖:pywin32(仅 Windows 且已安装 Microsoft Excel 时可用)。 逻辑:由 loader_excel._convert_xls_to_xlsx 在 soffice 失败后按需调用。 """ from __future__ import annotations import os import subprocess import sys import threading import time import ctypes from pathlib import Path def _list_excel_pids() -> set[int]: if os.name != "nt": return set() try: proc = subprocess.run( ["tasklist", "/FO", "CSV", "/NH", "/FI", "IMAGENAME eq EXCEL.EXE"], capture_output=True, text=True, check=False, ) except Exception: return set() out: set[int] = set() for line in (proc.stdout or "").splitlines(): line = line.strip() if not line or line.startswith("INFO:"): continue cols = [part.strip().strip('"') for part in line.split('","')] if len(cols) < 2: cols = [part.strip().strip('"') for part in line.split(",")] if len(cols) < 2: continue try: out.add(int(cols[1])) except ValueError: continue return out def _kill_excel_pids(pids: set[int]) -> None: if os.name != "nt": return for pid in sorted(pids): try: subprocess.run( ["taskkill", "/PID", str(pid), "/F"], capture_output=True, text=True, check=False, ) except Exception: continue def _excel_timeout_sec() -> int: raw = str(os.environ.get("EDKB_EXCEL_TIMEOUT_SEC", "120")).strip() try: value = int(raw) except ValueError: value = 120 return max(value, 10) def _should_accept_excel_dialog( window_title: str, child_texts: list[str], button_texts: list[str] ) -> bool: text_blob = "\n".join(x.strip().lower() for x in child_texts if x.strip()) if not text_blob: return False has_repair_prompt = any( token in text_blob for token in [ "损坏", "是否仍要打开", "corrupted", "do you still want to open", "repair", "修复", ] ) if not has_repair_prompt: return False return any( text.strip().lower().startswith(("是", "yes")) or "&y" in text.lower() for text in button_texts ) def _start_excel_dialog_watcher() -> tuple[threading.Event, threading.Thread | None]: stop_event = threading.Event() if os.name != "nt": return stop_event, None def _window_text(user32, hwnd: int) -> str: length = user32.GetWindowTextLengthW(hwnd) if length <= 0: return "" buf = ctypes.create_unicode_buffer(length + 1) user32.GetWindowTextW(hwnd, buf, length + 1) return buf.value def _class_name(user32, hwnd: int) -> str: buf = ctypes.create_unicode_buffer(256) user32.GetClassNameW(hwnd, buf, 255) return buf.value def _click_yes_if_needed() -> None: user32 = ctypes.windll.user32 bm_click = 0x00F5 vk_return = 0x0D wm_keydown = 0x0100 wm_keyup = 0x0101 while not stop_event.is_set(): windows: list[int] = [] @ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p) def enum_windows(hwnd, lparam): windows.append(int(hwnd)) return True user32.EnumWindows(enum_windows, 0) for hwnd in windows: title = _window_text(user32, hwnd) cls = _class_name(user32, hwnd).lower() if "Microsoft Excel" not in title and cls != "#32770": continue child_hwnds: list[int] = [] @ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p) def enum_children(child_hwnd, lparam): child_hwnds.append(int(child_hwnd)) return True user32.EnumChildWindows(hwnd, enum_children, 0) child_texts = [_window_text(user32, child) for child in child_hwnds] button_hwnds = [ child for child in child_hwnds if _class_name(user32, child).lower() == "button" ] button_texts = [_window_text(user32, child) for child in button_hwnds] if not _should_accept_excel_dialog(title, child_texts, button_texts): continue user32.SetForegroundWindow(hwnd) for child, text in zip(button_hwnds, button_texts): normalized = text.strip().lower() if normalized.startswith(("是", "yes")) or "&y" in normalized: user32.SendMessageW(child, bm_click, 0, 0) break else: user32.PostMessageW(hwnd, wm_keydown, vk_return, 0) user32.PostMessageW(hwnd, wm_keyup, vk_return, 0) stop_event.wait(0.5) thread = threading.Thread(target=_click_yes_if_needed, daemon=True) thread.start() return stop_event, thread def convert_with_excel(path: Path, output: Path, file_format: int = 51) -> Path: """ Excel COM conversion. 51 = xlOpenXMLWorkbook (.xlsx) """ timeout = _excel_timeout_sec() before_pids = _list_excel_pids() cmd = [ sys.executable, "-m", "edkb_system.skills.excel_bridge", str(path), str(output), str(file_format), ] try: proc = subprocess.run( cmd, capture_output=True, text=True, timeout=timeout, check=False, ) except subprocess.TimeoutExpired as exc: after_pids = _list_excel_pids() _kill_excel_pids(after_pids - before_pids) raise RuntimeError( f"Excel conversion timed out after {timeout}s: {path.name}" ) from exc if proc.returncode != 0: err = (proc.stderr or proc.stdout or "unknown error").strip() raise RuntimeError(f"Excel conversion failed: {err}") if not output.exists() or output.stat().st_size <= 0: raise RuntimeError(f"Excel conversion produced no output: {output}") return output def _child_main(argv: list[str]) -> int: if len(argv) != 4: print("usage: excel_bridge ", file=sys.stderr) return 2 src = Path(argv[1]).resolve() out = Path(argv[2]).resolve() file_format = int(argv[3]) out.parent.mkdir(parents=True, exist_ok=True) stop_event, watcher = _start_excel_dialog_watcher() excel = None wb = None try: from win32com.client import DispatchEx excel = DispatchEx("Excel.Application") excel.Visible = False excel.DisplayAlerts = 0 wb = excel.Workbooks.Open( Filename=str(src), ReadOnly=True, UpdateLinks=0, IgnoreReadOnlyRecommended=True, ) # xlOpenXMLWorkbook = 51 wb.SaveAs(str(out), FileFormat=file_format) finally: stop_event.set() if watcher is not None: watcher.join(timeout=1) if wb is not None: try: wb.Close(False) except Exception: pass if excel is not None: try: excel.Quit() except Exception: pass return 0 if __name__ == "__main__": raise SystemExit(_child_main(sys.argv))