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:
2026-09-28 10:23:42 +08:00
parent d4f83b0694
commit afea58fe17
3 changed files with 78 additions and 3 deletions
+3 -2
View File
@@ -210,8 +210,9 @@ description: 结构化修改表格文件。内容定位(列名 + 值),最
- 公式调整范围:目标表内引用、他表→目标表的跨表引用都会改;目标表→他表的引用不动(同 Excel)。
被删区域端点的区间按 Excel 语义收缩;命名范围(Tax2023 之类)不改写,引用它们的结果可能错位,需人工核对。
- 删除跨越合并区域边界的行/列会被拒绝(行为无法推断),改为整块删或先拆合并。
- 公式缓存值不由本工具计算:交付文件带「打开时全量重算」标记,Excel/WPS 打开会自动算;
若产物要进纯预览链路(截图/转 PDF/脚本读数),先用 LibreOffice 打开另存一次。
- 产物交付前已自动重算:LibreOffice 对 xlsx/xls/ods 求值并把结果写入公式缓存,可直接进预览/转 PDF/脚本读取;
重算失败时自动回退交付「未重算版」并在结果 `recalc` 字段标注 `failed:...`(未重算版仍带「打开时全量重算」标记,
Excel/WPS 打开结果一样正确);结果里看到 recalc=failed 时简短告知用户一句即可,不要重试。
- CSV 单元格一律按文本保留(「007」「1.10」不会变成 7/1.1);数字与数字文本在定位比较时互认。
- 多级表头、复杂合并:可能定位失败,需手工处理。
+45 -1
View File
@@ -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:
+30
View File
@@ -1,5 +1,6 @@
"""sheet-edit 的各个 op 实现。"""
import datetime
import shutil
import tempfile
from pathlib import Path
@@ -144,10 +145,12 @@ def apply(args):
except Exception:
_drop(out_path)
raise
recalc_note = _try_recalc(out_path, Path(td), lambda p: _verify_apply(p, before, plan))
return {
'ok': True,
'output': out_path.name,
'recalc': recalc_note,
'changes': [
{
'sheet': it['sheet'],
@@ -304,10 +307,13 @@ def insert_rows(args):
except Exception:
_drop(out_path)
raise
recalc_note = _try_recalc(out_path, Path(td),
lambda p: _verify_struct(p, before, sheet, 'row', insert_at, count, False, expected_new))
return {
'ok': True,
'output': out_path.name,
'recalc': recalc_note,
'sheet': sheet,
'inserted_at': insert_at,
'count': count,
@@ -345,10 +351,13 @@ def delete_rows(args):
except Exception:
_drop(out_path)
raise
recalc_note = _try_recalc(out_path, Path(td),
lambda p: _verify_struct(p, before, sheet, 'row', start, count, True, {}))
return {
'ok': True,
'output': out_path.name,
'recalc': recalc_note,
'sheet': sheet,
'deleted_at': start,
'count': count,
@@ -400,10 +409,13 @@ def insert_cols(args):
except Exception:
_drop(out_path)
raise
recalc_note = _try_recalc(out_path, Path(td),
lambda p: _verify_struct(p, before, sheet, 'col', insert_at, count, False, expected_new))
return {
'ok': True,
'output': out_path.name,
'recalc': recalc_note,
'sheet': sheet,
'inserted_at': insert_at,
'count': count,
@@ -443,10 +455,13 @@ def delete_cols(args):
except Exception:
_drop(out_path)
raise
recalc_note = _try_recalc(out_path, Path(td),
lambda p: _verify_struct(p, before, sheet, 'col', start, count, True, {}))
return {
'ok': True,
'output': out_path.name,
'recalc': recalc_note,
'sheet': sheet,
'deleted_at': start,
'count': count,
@@ -533,6 +548,21 @@ def _drop(path: Path):
pass
def _try_recalc(out_path, work_dir, verify):
"""正确性门禁通过后尝试 LO 重算;重算产物同样过一遍 verify 才能覆盖交付,
否则保持未重算版(仍带 fullCalcOnLoad 标记,Excel/WPS 打开会自动算)。
重算是可用性增强不是正确性条件,故失败只降级不报错。返回状态供结果 JSON。"""
cand, err = convert.recalc(out_path, work_dir)
if cand is None:
return 'skipped' if '无需重算' in (err or '') else f'failed: {err}'
try:
verify(cand)
except Exception as e:
return f'failed: 重算产物未过自检,交付未重算版({str(e)[:120]})'
shutil.copy2(cand, out_path)
return 'done'
def _adjust_formulas(wb, target_sheet, axis, at, count, delete):
"""全工作簿调整公式:含「其他表引用目标表」的跨表公式;目标表引用他表的不动(同 Excel)。