Files
syops/backend/edkb_system/skills/loader_excel.py
T

87 lines
2.7 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.
"""
backend/edkb_system/skills/loader_excel.py
文件用途:加载 Excel 表格为结构化数据
说明:
- .xls 旧格式先经 soffice_util 转为 .xlsx,再走 openpyxl 解析。
"""
from __future__ import annotations
from pathlib import Path
from openpyxl import load_workbook
from edkb_system.contracts import Context
from edkb_system.skills.soffice_util import convert_with_soffice, soffice_candidates
def _convert_xls_to_xlsx(path: Path, out_dir: Path) -> Path:
"""将 .xls 转为 .xlsx;soffice 调用带超时,见 EDKB_SOFFICE_TIMEOUT_SEC。"""
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
try:
proc = convert_with_soffice(
soffice,
convert_to="xlsx",
source_path=path,
out_dir=out_dir,
)
except FileNotFoundError:
errors.append(f"soffice not found: {soffice}")
continue
except RuntimeError as exc:
errors.append(str(exc))
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