perf(固资管理): 优化固资管理模糊查询提升用户体验
This commit is contained in:
1 parent
d3cfd24d6f
commit
b079524b4f
3 files changed
+513
-71
No files matched your search
@@ -7,52 +7,251 @@ backend/edkb_system/skills/excel_bridge.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import ctypes
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def convert_with_excel(path: Path, output: Path) -> Path:
|
||||
"""
|
||||
使用 Microsoft Excel COM 将源表格另存为 .xlsx。
|
||||
|
||||
核心逻辑:启动 Excel.Application → Open → SaveAs(xlsx) → Quit。
|
||||
|
||||
Args:
|
||||
path: 源 .xls 文件路径。
|
||||
output: 目标 .xlsx 路径。
|
||||
|
||||
Returns:
|
||||
成功写入的 output 路径。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 非 Windows、缺少 pywin32/Excel,或转换未产出目标文件。
|
||||
"""
|
||||
import os
|
||||
|
||||
def _list_excel_pids() -> set[int]:
|
||||
if os.name != "nt":
|
||||
raise RuntimeError("Excel COM conversion is only available on Windows")
|
||||
|
||||
return set()
|
||||
try:
|
||||
import win32com.client
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("Excel COM conversion requires pywin32 on Windows") from exc
|
||||
proc = subprocess.run(
|
||||
["tasklist", "/FO", "CSV", "/NH", "/FI", "IMAGENAME eq EXCEL.EXE"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
except Exception:
|
||||
return set()
|
||||
|
||||
source = str(path.resolve())
|
||||
target = str(output.resolve())
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
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
|
||||
|
||||
excel = win32com.client.Dispatch("Excel.Application")
|
||||
excel.Visible = False
|
||||
excel.DisplayAlerts = False
|
||||
workbook = None
|
||||
|
||||
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:
|
||||
workbook = excel.Workbooks.Open(source)
|
||||
# 51 = xlOpenXMLWorkbook (.xlsx)
|
||||
workbook.SaveAs(target, FileFormat=51)
|
||||
finally:
|
||||
if workbook is not None:
|
||||
workbook.Close(SaveChanges=False)
|
||||
excel.Quit()
|
||||
value = int(raw)
|
||||
except ValueError:
|
||||
value = 120
|
||||
return max(value, 10)
|
||||
|
||||
if not output.exists():
|
||||
raise RuntimeError(f"Excel COM did not produce output file: {output}")
|
||||
|
||||
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 <input> <output> <file_format>", 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))
|
||||
Reference in new issue
Block a user