sheet-edit 公式自动重算(评审确认版):写操作产物交付前经 LibreOffice 同格式转换强制求值写回缓存——openpyxl 产物无缓存、LO 保存必须求值,实测重算必达且公式文本保留,产物可直接进预览/转PDF/data_only 读取,不再依赖用户手动打开;_libreoffice 全链路加 -env:UserInstallation 隔离 profile(实测无隔离时 read-only rootfs 下 rc=77 必崩,顺带根治并发转换单实例锁冲突);重算作为可用性增强置于正确性门禁之后且需再过一次自检,任何失败自动回退交付已验证的未重算版并标 recalc=failed,结果加 recalc 字段(done/skipped/failed);否决评审的宏 calculateAll 方案(实测连 OOXMLRecalcMode 都不用设);csv 跳过;SKILL.md 边界同步改口径
This commit is contained in:
@@ -76,11 +76,21 @@ def from_workbook(xlsx: Path, dst: Path, original_ext: str):
|
||||
|
||||
# ---------- 内部 ----------
|
||||
|
||||
def _lo_profile(out_dir: Path) -> Path:
|
||||
"""LO 隔离 profile:执行容器根文件系统只读,默认 ~/.config 写入会直接 rc=77 崩(实测);
|
||||
每次调用独立 profile 同时解决并发转换的 LO 单实例锁冲突。"""
|
||||
prof = out_dir / 'loprofile'
|
||||
(prof / 'user').mkdir(parents=True, exist_ok=True)
|
||||
return prof
|
||||
|
||||
|
||||
def _libreoffice(src: Path, out_dir: Path, target_ext: str) -> Path:
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = target_ext.lstrip('.')
|
||||
r = subprocess.run(
|
||||
['libreoffice', '--headless', '--convert-to', target,
|
||||
['libreoffice', '--headless', '--norestore',
|
||||
'-env:UserInstallation=' + _lo_profile(out_dir).as_uri(),
|
||||
'--convert-to', target,
|
||||
'--outdir', str(out_dir), str(src)],
|
||||
capture_output=True, text=True, timeout=180,
|
||||
)
|
||||
@@ -93,6 +103,40 @@ def _libreoffice(src: Path, out_dir: Path, target_ext: str) -> Path:
|
||||
return expected
|
||||
|
||||
|
||||
# 重算适用的二进制/文档格式(csv 无缓存概念,跳过)
|
||||
RECALC_EXTS = {'.xlsx', '.xls', '.ods'}
|
||||
|
||||
|
||||
def recalc(path: Path, work_dir: Path):
|
||||
"""LibreOffice 强制重算公式缓存值:openpyxl 产物无缓存,LO 加载时必须求值才能保存,
|
||||
实测(LO 7.4)重算结果会写入缓存元素且公式文本保留。
|
||||
|
||||
返回 (重算产物路径, None) 或 (None, 失败原因);不抛异常,是否回退由调用方决策。
|
||||
注意返回的文件在 work_dir 内,调用方需在同一生命周期内用完。"""
|
||||
ext = path.suffix.lower()
|
||||
if ext not in RECALC_EXTS:
|
||||
return None, f"{ext} 格式无需重算"
|
||||
out_dir = work_dir / 'recalc'
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
expected = out_dir / path.name
|
||||
try:
|
||||
r = subprocess.run(
|
||||
['libreoffice', '--headless', '--norestore',
|
||||
'-env:UserInstallation=' + _lo_profile(out_dir).as_uri(),
|
||||
'--convert-to', ext[1:],
|
||||
'--outdir', str(out_dir), str(path)],
|
||||
capture_output=True, text=True, timeout=180,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
return None, "LibreOffice 不可用"
|
||||
except subprocess.TimeoutExpired:
|
||||
return None, "LibreOffice 重算超时(180s)"
|
||||
if r.returncode != 0 or not expected.exists():
|
||||
msg = (r.stderr or r.stdout).strip()[:150] or '无输出'
|
||||
return None, f"LibreOffice 重算失败: {msg}"
|
||||
return expected, None
|
||||
|
||||
|
||||
def _read_csv(path: Path):
|
||||
last_err = None
|
||||
for enc in _CSV_ENCODINGS:
|
||||
|
||||
Reference in New Issue
Block a user