120 lines
3.8 KiB
Python
120 lines
3.8 KiB
Python
"""
|
||
backend/edkb_system/skills/loader_excel.py
|
||
文件用途:加载 Excel 表格为结构化数据
|
||
|
||
说明:
|
||
- .xls 旧格式先经 soffice_util 转为 .xlsx,再走 openpyxl 解析。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
from pathlib import Path
|
||
|
||
from openpyxl import load_workbook, Workbook
|
||
|
||
from edkb_system.contracts import Context
|
||
from edkb_system.skills.soffice_util import convert_with_soffice, soffice_candidates
|
||
|
||
|
||
def _convert_xls_to_xlsx_python(path: Path, output: Path) -> Path:
|
||
"""使用 xlrd 和 openpyxl 进行纯 Python 转换。"""
|
||
import xlrd
|
||
|
||
book = xlrd.open_workbook(str(path))
|
||
wb = Workbook()
|
||
wb.remove(wb.active) # 移除默认的 Sheet
|
||
|
||
for i in range(book.nsheets):
|
||
sheet = book.sheet_by_index(i)
|
||
new_ws = wb.create_sheet(title=sheet.name)
|
||
for row in range(sheet.nrows):
|
||
# 将 xlrd 的行值(list)追加到 openpyxl 的 sheet 中
|
||
new_ws.append(sheet.row_values(row))
|
||
|
||
wb.save(str(output))
|
||
return output
|
||
|
||
|
||
def _convert_xls_to_xlsx(path: Path, out_dir: Path) -> Path:
|
||
"""将 .xls 转为 .xlsx。依次尝试 soffice、Excel COM 和 xlrd。"""
|
||
out_dir.mkdir(parents=True, exist_ok=True)
|
||
output = out_dir / f"{path.stem}.xlsx"
|
||
errors: list[str] = []
|
||
|
||
# 1. 尝试 LibreOffice (soffice)
|
||
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,
|
||
)
|
||
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'}"
|
||
)
|
||
except Exception as exc:
|
||
errors.append(f"soffice attempt failed ({soffice}): {exc}")
|
||
|
||
# 2. Windows 环境下尝试 Excel COM
|
||
if os.name == "nt":
|
||
try:
|
||
from edkb_system.skills.excel_bridge import convert_with_excel
|
||
|
||
return convert_with_excel(path, output)
|
||
except Exception as exc:
|
||
errors.append(f"Excel COM conversion failed: {exc}")
|
||
|
||
# 3. 最后尝试纯 Python (xlrd)
|
||
try:
|
||
return _convert_xls_to_xlsx_python(path, output)
|
||
except Exception as exc:
|
||
errors.append(f"Python xlrd conversion failed: {exc}")
|
||
|
||
joined = "; ".join(errors) if errors else "no converter attempted"
|
||
raise RuntimeError(
|
||
".xls 转 .xlsx 失败。请安装 LibreOffice(soffice)、Microsoft Excel 或检查文件。"
|
||
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
|