Files
syops/backend/edkb_system/skills/loader_excel.py
T
2026-05-12 08:16:42 +08:00

90 lines
2.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
import os
import subprocess
from pathlib import Path
from openpyxl import load_workbook
from edkb_system.contracts import Context
def _soffice_candidates() -> list[str]:
return [
os.environ.get("EDKB_SOFFICE", "").strip(),
r"C:\Program Files\LibreOffice\program\soffice.exe",
r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
"soffice",
]
def _convert_xls_to_xlsx(path: Path, out_dir: Path) -> Path:
out_dir.mkdir(parents=True, exist_ok=True)
output = out_dir / f"{path.stem}.xlsx"
errors: list[str] = []
for soffice in _soffice_candidates():
if not soffice:
continue
cmd = [
soffice,
"--headless",
"--convert-to",
"xlsx",
str(path),
"--outdir",
str(out_dir),
]
try:
proc = subprocess.run(cmd, capture_output=True, text=True)
except FileNotFoundError:
errors.append(f"soffice not found: {soffice}")
continue
if proc.returncode == 0 and output.exists():
return output
stderr = (proc.stderr or "").strip()
errors.append(
f"soffice failed ({soffice}, code={proc.returncode}): {stderr or 'no stderr'}"
)
joined = "; ".join(errors) if errors else "no converter attempted"
raise RuntimeError(
".xls 转 .xlsx 失败。请安装 LibreOffice(soffice)或设置 EDKB_SOFFICE。"
f" details: {joined}"
)
def _norm(v) -> str:
return "" if v is None else str(v).strip()
def _trim_trailing_empty(vals: list[str]) -> list[str]:
end = len(vals)
while end > 0 and not vals[end - 1]:
end -= 1
return vals[:end]
def run(input_data: dict, context: Context) -> list[dict]:
file_path = Path(input_data["file_path"])
work_dir = Path(input_data["work_dir"])
if file_path.suffix.lower() == ".xls":
file_path = _convert_xls_to_xlsx(file_path, work_dir)
wb = load_workbook(str(file_path), data_only=True)
tables: list[dict] = []
for ws in wb.worksheets:
rows: list[list[str]] = []
for row in ws.iter_rows(values_only=True):
vals = _trim_trailing_empty([_norm(v) for v in row])
if any(vals):
rows.append(vals)
if not rows:
continue
width = max(len(r) for r in rows)
normalized = [r + [""] * (width - len(r)) for r in rows]
tables.append(
{"sheet": ws.title, "headers": normalized[0], "rows": normalized[1:]}
)
context.extras["tables_count"] = len(tables)
return tables