sheet-edit 技能评审修复(P0/P1 全绿):公式调整弃裸正则、改用官方 Tokenizer 按 subtype=RANGE 逐 token 重写——LOG10/ATAN2 函数名、"B2" 字符串、本表引用他表不再被错改,他表→目标表跨表引用获得调整(同 Excel),区间删除按 Excel 语义收缩而非裸 #REF!,已失效 #REF! 透传不炸;合并区域随插删移动(修 mv 误同时移行移列致 D4:D5→E5:E6 吞数据的笔误;跨界删除拒绝)、合并区非锚点写入显式报错;insert/delete 补结构化自检(逐格坐标映射+公式预期+尺寸+新带 fill 校验),校验失败自动删产物兑现「不交付」;inspect 日期/ArrayFormula JSON 化(旧版含日期表直接崩)、formulas 上限 500+truncated、返回 merged;CSV 不再 coerce(007/1.10 保真),value_eq 数字↔数字文本互认;openpyxl 丢公式缓存值的对策=保存置 fullCalcOnLoad;output 文件名消毒;SKILL.md 边界/常见错误同步重写
This commit is contained in:
@@ -0,0 +1,214 @@
|
||||
---
|
||||
name: sheet-edit
|
||||
description: 结构化修改表格文件。内容定位(列名 + 值),最小改动。支持改值、改公式、插入/删除行列,公式引用自动调整。
|
||||
---
|
||||
|
||||
# sheet-edit
|
||||
|
||||
## 何时使用
|
||||
|
||||
- 修改表格文件中的单元格值或公式
|
||||
- 插入、删除行或列
|
||||
- 按内容定位目标行/列
|
||||
|
||||
支持格式:`.xls`、`.xlsx`、`.csv`、`.ods`。
|
||||
|
||||
不适用:新建工作簿、生成图表、执行宏。
|
||||
|
||||
## 工作流程
|
||||
|
||||
1. `op=inspect` 查看表结构与公式
|
||||
2. 按需求选择 `op=apply` / `op=insert_rows` / `op=delete_rows` / `op=insert_cols` / `op=delete_cols`
|
||||
|
||||
## inspect
|
||||
|
||||
读取表结构、单元格值、公式。
|
||||
|
||||
```json
|
||||
{"op": "inspect", "file": "预算表.xlsx"}
|
||||
```
|
||||
|
||||
参数:
|
||||
- `file`(必填):相对任务目录的路径
|
||||
- `sheet`(可选):只查指定 sheet
|
||||
- `limit`(可选):每个 sheet 预览行数,默认 50
|
||||
- `header_row`(可选):表头行号,默认 1
|
||||
|
||||
返回示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"sheets": [
|
||||
{
|
||||
"name": "明细",
|
||||
"rows": 10,
|
||||
"cols": 7,
|
||||
"header_row": 1,
|
||||
"headers": ["序号", "项目", "单位", "数量", "单价", "金额", "备注"],
|
||||
"preview": [
|
||||
[1, "管道", "米", 100, 18, {"formula": "=D3*E3"}, ""],
|
||||
[2, "顶管", "米", 50, 157, {"formula": "=D4*E4"}, ""]
|
||||
],
|
||||
"formulas": [
|
||||
{"cell": "F3", "formula": "=D3*E3"},
|
||||
{"cell": "F4", "formula": "=D4*E4"}
|
||||
],
|
||||
"truncated": false
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
要点:
|
||||
- `headers` 是表头行;合并单元格只有首个有值,其余为 `null`
|
||||
- 公式以 `{"formula": "=..."}` 表示
|
||||
- `preview` 可能被 `limit` 截断;`formulas` 最多列 500 条(超出时 `formulas_truncated: true`)
|
||||
- `merged` 是合并区域列表(如 `["A1:G1"]`)
|
||||
- `truncated` 为 `true` 时预览被截断,改动仍可命中整张表
|
||||
|
||||
## apply(改值/改公式)
|
||||
|
||||
```json
|
||||
{
|
||||
"op": "apply",
|
||||
"file": "预算表.xlsx",
|
||||
"changes": [
|
||||
{
|
||||
"sheet": "明细",
|
||||
"match": {"项目": "顶管"},
|
||||
"set": {"单价": {"old": 157, "new": 180}}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
参数:
|
||||
- `file`(必填)
|
||||
- `changes`(必填):改动清单
|
||||
- `header_row`(可选,默认 1)
|
||||
- `output`(可选):输出文件名(只能是文件名,不能含路径),默认原文件名加「(已改)」
|
||||
|
||||
### 定位
|
||||
|
||||
`match` 用列名 + 值定位目标行,可多列组合:
|
||||
|
||||
```json
|
||||
{"match": {"项目": "顶管", "单位": "米"}}
|
||||
```
|
||||
|
||||
`set` 指定要改的列和新旧值:
|
||||
|
||||
```json
|
||||
{"set": {"单价": {"old": 157, "new": 180}}}
|
||||
```
|
||||
|
||||
`old` 必须与实际值一致,否则整体报错,不做任何改动。
|
||||
|
||||
### 改公式
|
||||
|
||||
`new` 以 `=` 开头即为公式;`old` 用字符串精确匹配:
|
||||
|
||||
```json
|
||||
{"set": {"金额": {"old": "=D3*E3", "new": "=D3*E3*1.1"}}}
|
||||
```
|
||||
|
||||
### 一次改多处
|
||||
|
||||
`changes` 可包含多项,跨 sheet 也可以。
|
||||
|
||||
## insert_rows / delete_rows
|
||||
|
||||
**insert_rows**:
|
||||
|
||||
```json
|
||||
{
|
||||
"op": "insert_rows",
|
||||
"file": "预算表.xlsx",
|
||||
"sheet": "明细",
|
||||
"after_match": {"项目": "顶管"},
|
||||
"count": 1,
|
||||
"fill": {"序号": 3, "项目": "新增项", "单位": "米", "数量": 20, "单价": 100, "金额": "=D4*E4"}
|
||||
}
|
||||
```
|
||||
|
||||
- `after_match`:在此行之后插入(用列名 + 值定位)
|
||||
- `count`:插入行数,默认 1
|
||||
- `fill`:可选,为新行填充值(公式按新行实际行号自己写好);以 `=` 开头视为公式
|
||||
|
||||
**delete_rows**:
|
||||
|
||||
```json
|
||||
{
|
||||
"op": "delete_rows",
|
||||
"file": "预算表.xlsx",
|
||||
"sheet": "明细",
|
||||
"match": {"项目": "顶管"},
|
||||
"count": 1
|
||||
}
|
||||
```
|
||||
|
||||
- `match`:要删除的行
|
||||
- `count`:删除行数,默认 1
|
||||
|
||||
行插入/删除会**自动调整公式引用**(含其他工作表中引用本表的跨表公式,同 Excel);合并单元格同步移动,区域内插行会自动扩大区域。
|
||||
|
||||
## insert_cols / delete_cols
|
||||
|
||||
**insert_cols**:
|
||||
|
||||
```json
|
||||
{
|
||||
"op": "insert_cols",
|
||||
"file": "预算表.xlsx",
|
||||
"sheet": "明细",
|
||||
"after": "单价",
|
||||
"count": 1,
|
||||
"fill_header": "折扣"
|
||||
}
|
||||
```
|
||||
|
||||
- `after`:在此列之后插入(用列名定位)
|
||||
- `fill_header`:可选,新列的表头
|
||||
|
||||
**delete_cols**:
|
||||
|
||||
```json
|
||||
{
|
||||
"op": "delete_cols",
|
||||
"file": "预算表.xlsx",
|
||||
"sheet": "明细",
|
||||
"col": "备注",
|
||||
"count": 1
|
||||
}
|
||||
```
|
||||
|
||||
列插入/删除同样会**自动调整公式引用**。
|
||||
|
||||
## 硬约束
|
||||
|
||||
- 只改清单里指定的位置
|
||||
- 改动前校验 `old`(set)或 `match` 唯一性
|
||||
- 改动后自检:目标改动生效、其他内容未变(含公式原文)、文件可打开
|
||||
- 任一项失败 → 产物自动删除、不交付
|
||||
- 遇不支持的引用形态(数组公式、外部簿引用、结构化引用)直接报错,绝不半改交付
|
||||
|
||||
## 边界
|
||||
|
||||
- 公式调整范围:目标表内引用、他表→目标表的跨表引用都会改;目标表→他表的引用不动(同 Excel)。
|
||||
被删区域端点的区间按 Excel 语义收缩;命名范围(Tax2023 之类)不改写,引用它们的结果可能错位,需人工核对。
|
||||
- 删除跨越合并区域边界的行/列会被拒绝(行为无法推断),改为整块删或先拆合并。
|
||||
- 公式缓存值不由本工具计算:交付文件带「打开时全量重算」标记,Excel/WPS 打开会自动算;
|
||||
若产物要进纯预览链路(截图/转 PDF/脚本读数),先用 LibreOffice 打开另存一次。
|
||||
- CSV 单元格一律按文本保留(「007」「1.10」不会变成 7/1.1);数字与数字文本在定位比较时互认。
|
||||
- 多级表头、复杂合并:可能定位失败,需手工处理。
|
||||
|
||||
## 常见错误
|
||||
|
||||
1. **match 不唯一**:多行满足条件,补充更多列条件
|
||||
2. **old 不匹配**:定位错了或数据已变,重新 inspect
|
||||
3. **表头不在第 1 行**:传 `header_row`
|
||||
4. **列名不存在**:报错会列出可用列名
|
||||
5. **sheet 不存在**:报错会列出可用 sheet 名
|
||||
6. **写入合并区域非锚点格**:报错提示改用区域左上角锚点
|
||||
7. **报「不支持数组公式/外部簿引用」**:该表需人工处理,不要反复重试
|
||||
@@ -0,0 +1,6 @@
|
||||
"""sheet-edit 内部库。"""
|
||||
|
||||
|
||||
class UserError(Exception):
|
||||
"""参数或使用错误,以清晰消息返回给调用方。"""
|
||||
pass
|
||||
@@ -0,0 +1,105 @@
|
||||
"""文件格式转换:统一用 xlsx 作为工作副本。
|
||||
|
||||
支持 .xls / .xlsx / .csv / .ods。转换走 LibreOffice(已预装)。
|
||||
"""
|
||||
import csv
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import openpyxl
|
||||
|
||||
from . import UserError
|
||||
|
||||
|
||||
SUPPORTED_EXTS = {'.xls', '.xlsx', '.csv', '.ods'}
|
||||
_CSV_ENCODINGS = ('utf-8-sig', 'utf-8', 'gbk', 'gb18030', 'latin-1')
|
||||
|
||||
|
||||
def check_supported(path: Path) -> str:
|
||||
ext = path.suffix.lower()
|
||||
if ext not in SUPPORTED_EXTS:
|
||||
raise UserError(
|
||||
f"不支持的格式: {ext}(支持: {', '.join(sorted(SUPPORTED_EXTS))})"
|
||||
)
|
||||
return ext
|
||||
|
||||
|
||||
def to_workbook(path: Path, work_dir: Path) -> Path:
|
||||
"""把输入文件转成 xlsx 工作副本,返回 xlsx 路径。"""
|
||||
ext = check_supported(path)
|
||||
work_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if ext == '.xlsx':
|
||||
dst = work_dir / path.name
|
||||
shutil.copy2(path, dst)
|
||||
return dst
|
||||
|
||||
if ext == '.csv':
|
||||
rows = _read_csv(path)
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = 'Sheet1'
|
||||
# CSV 是文本格式:原样保留字段字符串(不做数字 coerce),回写才算真「最小改动」
|
||||
for row in rows:
|
||||
ws.append(list(row))
|
||||
dst = work_dir / (path.stem + '.xlsx')
|
||||
wb.save(dst)
|
||||
return dst
|
||||
|
||||
return _libreoffice(path, work_dir, '.xlsx')
|
||||
|
||||
|
||||
def from_workbook(xlsx: Path, dst: Path, original_ext: str):
|
||||
"""把处理后的 xlsx 转回目标格式,写到 dst。"""
|
||||
ext = original_ext.lower()
|
||||
dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if ext == '.xlsx':
|
||||
shutil.copy2(xlsx, dst)
|
||||
return
|
||||
|
||||
if ext == '.csv':
|
||||
wb = openpyxl.load_workbook(xlsx, data_only=False)
|
||||
ws = wb.active
|
||||
with open(dst, 'w', encoding='utf-8-sig', newline='') as f:
|
||||
w = csv.writer(f)
|
||||
for row in ws.iter_rows(values_only=True):
|
||||
w.writerow(['' if v is None else v for v in row])
|
||||
return
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
produced = _libreoffice(xlsx, Path(td), ext)
|
||||
shutil.copy2(produced, dst)
|
||||
|
||||
|
||||
# ---------- 内部 ----------
|
||||
|
||||
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,
|
||||
'--outdir', str(out_dir), str(src)],
|
||||
capture_output=True, text=True, timeout=180,
|
||||
)
|
||||
if r.returncode != 0:
|
||||
msg = (r.stderr or r.stdout).strip() or '无输出'
|
||||
raise UserError(f"LibreOffice 转换失败: {msg}")
|
||||
expected = out_dir / (src.stem + target_ext)
|
||||
if not expected.exists():
|
||||
raise UserError(f"LibreOffice 未生成输出: {expected}")
|
||||
return expected
|
||||
|
||||
|
||||
def _read_csv(path: Path):
|
||||
last_err = None
|
||||
for enc in _CSV_ENCODINGS:
|
||||
try:
|
||||
with open(path, encoding=enc, newline='') as f:
|
||||
return list(csv.reader(f))
|
||||
except UnicodeDecodeError as e:
|
||||
last_err = e
|
||||
continue
|
||||
raise UserError(f"无法识别 CSV 编码: {path}(最后错误: {last_err})")
|
||||
@@ -0,0 +1,158 @@
|
||||
"""调整 Excel 公式中的单元格引用(插入/删除行列)。
|
||||
|
||||
基于 openpyxl 官方 Tokenizer 逐 token 重写,只动 RANGE——裸正则会犯的经典错误这里都不存在:
|
||||
- 函数名(LOG10(、ATAN2()是 OPEN token、字符串字面量是 TEXT token,永不触碰;
|
||||
- RANGE token 值自带 sheet 前缀(OTHER!D3:D9、'My Sheet'!A1),可以精确判断引用指向**哪张表**。
|
||||
|
||||
调整规则(对齐 Excel):
|
||||
- 无 sheet 前缀:公式所在表 == 目标表才动;
|
||||
- 有前缀:前缀 == 目标表才动;目标表公式引用其他表 → 不动(Excel 同样不动)。
|
||||
- 插入(delete=False):端点 >= at → +count(区间两端独立移动 = Excel 的区间扩张)。
|
||||
- 删除(count 行/列从 at 起):端点 >= at+count → -count;单引用落在删除区间内 → #REF!;
|
||||
区间端点落在删除区间内 → 收缩(起点→at、终点→at-1),与 Excel 行为一致;区间整体被删 → #REF!。
|
||||
- 绝对引用($A$1)同样移动——Excel 的插删会改写绝对引用(区别于复制填充)。
|
||||
|
||||
不静默改坏(遇到即 UserError 拒绝):
|
||||
- 外部簿引用([Book.xlsx]Sheet!A1);
|
||||
- 解析不了的结构化引用(Table1[金额] 之类)。
|
||||
不调整(保持原样,SKILL.md 有说明):
|
||||
- 命名范围(Tokenizer 归为非 RANGE token,天然不动)。
|
||||
"""
|
||||
import re
|
||||
|
||||
from openpyxl.formula.tokenizer import Tokenizer
|
||||
from openpyxl.utils import column_index_from_string, get_column_letter
|
||||
|
||||
from . import UserError
|
||||
|
||||
# RANGE 端点形态:$?COL$?ROW / $ROW / $COL
|
||||
_CELL_EP = re.compile(r'^(\$?)([A-Za-z]{1,3})(\$?)(\d+)$')
|
||||
_ROW_EP = re.compile(r'^(\$?)(\d+)$')
|
||||
_COL_EP = re.compile(r'^(\$?)([A-Za-z]{1,3})$')
|
||||
# 带引号的 sheet 前缀:'My Sheet'!A1
|
||||
_QUOTED_PREFIX = re.compile(r"^'([^']*)'!(.+)$", re.S)
|
||||
|
||||
|
||||
def _norm_sheet(name):
|
||||
return str(name).strip().lower()
|
||||
|
||||
|
||||
def _split_ref(value):
|
||||
"""'OTHER!D3:D9' → ('OTHER', 'D3:D9');'D3' → (None, 'D3')。"""
|
||||
if value.startswith("'"):
|
||||
m = _QUOTED_PREFIX.match(value)
|
||||
if m:
|
||||
return m.group(1), m.group(2)
|
||||
raise UserError(f"不支持的引用语法:{value!r}")
|
||||
if '!' in value:
|
||||
sheet, rest = value.split('!', 1)
|
||||
if sheet.startswith('[') or '[' in sheet:
|
||||
raise UserError(f"不支持外部工作簿引用:{value!r}(请先把跨簿公式改成本表/本簿引用)")
|
||||
return sheet, rest
|
||||
return None, value
|
||||
|
||||
|
||||
def _endpoint_axis_shape(ep):
|
||||
"""返回 (kind, col_letters_or_None, row_num_or_None, col_abs, row_abs)。"""
|
||||
m = _CELL_EP.match(ep)
|
||||
if m:
|
||||
col_abs, col, row_abs, row = m.groups()
|
||||
return 'cell', col.upper(), int(row), col_abs, row_abs
|
||||
m = _ROW_EP.match(ep)
|
||||
if m:
|
||||
return 'row', None, int(m.group(2)), '', m.group(1)
|
||||
m = _COL_EP.match(ep)
|
||||
if m:
|
||||
return 'col', m.group(2).upper(), None, m.group(1), ''
|
||||
raise UserError(f"不支持的引用语法(结构化引用/特殊形式):{ep!r}")
|
||||
|
||||
|
||||
def _shift_pair(nums, at, count, delete):
|
||||
"""区间两端点在同一轴上的数值移动;返回 None 表示整体失效(#REF!)。"""
|
||||
out = []
|
||||
for i, v in enumerate(nums):
|
||||
if not delete:
|
||||
out.append(v + count if v >= at else v)
|
||||
elif v < at:
|
||||
out.append(v)
|
||||
elif v < at + count:
|
||||
if len(nums) == 1:
|
||||
return [None]
|
||||
out.append(at if i == 0 else at - 1)
|
||||
else:
|
||||
out.append(v - count)
|
||||
if len(out) == 2 and out[1] < out[0]:
|
||||
return [None, None]
|
||||
return out
|
||||
|
||||
|
||||
def _shift_endpoint_set(eps, axis, at, count, delete):
|
||||
"""移动一组端点(1 个=单引用,2 个=区间),返回新端点字符串列表。"""
|
||||
shapes = [_endpoint_axis_shape(e) for e in eps]
|
||||
nums = []
|
||||
for kind, col, row, col_abs, row_abs in shapes:
|
||||
if kind == 'cell':
|
||||
nums.append(row if axis == 'row' else column_index_from_string(col))
|
||||
elif kind == 'row':
|
||||
nums.append(row if axis == 'row' else None)
|
||||
else: # col
|
||||
nums.append(None if axis == 'row' else column_index_from_string(col))
|
||||
if any(n is None for n in nums):
|
||||
return eps # 本轴不涉及的引用(整列引用遇行操作等)原样返回
|
||||
moved = _shift_pair(nums, at, count, delete)
|
||||
if moved[0] is None:
|
||||
return ['#REF!'] if len(eps) == 1 else ['#REF!', '#REF!']
|
||||
new_eps = []
|
||||
for (kind, col, row, col_abs, row_abs), v in zip(shapes, moved):
|
||||
if kind == 'cell':
|
||||
if axis == 'row':
|
||||
new_eps.append(f'{col_abs}{col}{row_abs}{v}')
|
||||
else:
|
||||
new_eps.append(f'{col_abs}{get_column_letter(v)}{row_abs}{row}')
|
||||
elif kind == 'row':
|
||||
new_eps.append(f'{row_abs}{v}')
|
||||
else:
|
||||
new_eps.append(f'{col_abs}{get_column_letter(v)}')
|
||||
return new_eps
|
||||
|
||||
|
||||
def shift_formula(formula, owner_sheet, target_sheet, axis, at, count, delete=False):
|
||||
"""重写一条公式中所有指向 target_sheet 的引用。
|
||||
|
||||
owner_sheet: 公式所在表的表名;axis: 'row' | 'col';at: 1-based 起始行/列。
|
||||
未被命中的公式原串返回(不经 Tokenizer 重组,零副作用)。
|
||||
"""
|
||||
if not isinstance(formula, str) or not formula.startswith('='):
|
||||
return formula
|
||||
try:
|
||||
items = Tokenizer(formula).items
|
||||
except UserError:
|
||||
raise
|
||||
except Exception:
|
||||
raise UserError(f"公式语法解析失败(不支持的公式形式):{formula!r}")
|
||||
items = Tokenizer(formula).items
|
||||
touched = False
|
||||
for tok in items:
|
||||
# openpyxl 3.1:引用格的判别是 type='OPERAND' + subtype='RANGE'(type 只到大类)
|
||||
if getattr(tok, 'subtype', None) != 'RANGE':
|
||||
continue
|
||||
if '#REF' in tok.value:
|
||||
continue # 已失效引用:Excel 不会再调整它,原样保留
|
||||
sheet, body = _split_ref(tok.value)
|
||||
if sheet is None:
|
||||
points_target = _norm_sheet(owner_sheet) == _norm_sheet(target_sheet)
|
||||
else:
|
||||
points_target = _norm_sheet(sheet) == _norm_sheet(target_sheet)
|
||||
if not points_target:
|
||||
continue
|
||||
prefix_raw = tok.value[: len(tok.value) - len(body)]
|
||||
eps = body.split(':') if ':' in body else [body]
|
||||
if len(eps) > 2:
|
||||
raise UserError(f"不支持 3D/多段引用:{tok.value!r}")
|
||||
new_val = prefix_raw + ':'.join(_shift_endpoint_set(eps, axis, at, count, delete))
|
||||
if new_val != tok.value:
|
||||
tok.value = new_val
|
||||
touched = True
|
||||
if not touched:
|
||||
return formula
|
||||
return '=' + ''.join(t.value for t in items)
|
||||
@@ -0,0 +1,75 @@
|
||||
"""内容定位:用列名 + 值找目标行/列。"""
|
||||
from . import UserError
|
||||
|
||||
|
||||
def is_formula(v) -> bool:
|
||||
return isinstance(v, str) and v.startswith('=')
|
||||
|
||||
|
||||
def value_eq(a, b) -> bool:
|
||||
if a is None and b is None:
|
||||
return True
|
||||
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
|
||||
return abs(float(a) - float(b)) < 1e-9
|
||||
# 数字↔数字文本(CSV 往返后数值变文本,定位比较要能对上)
|
||||
if isinstance(a, str) != isinstance(b, str):
|
||||
try:
|
||||
return abs(float(a) - float(b)) < 1e-9
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return a == b
|
||||
|
||||
|
||||
def build_col_map(ws, header_row: int) -> dict:
|
||||
"""从表头行构建 {列名: 列号}。"""
|
||||
col_map = {}
|
||||
for c in range(1, ws.max_column + 1):
|
||||
v = ws.cell(header_row, c).value
|
||||
if v is None:
|
||||
continue
|
||||
name = str(v).strip()
|
||||
if not name:
|
||||
continue
|
||||
if name in col_map:
|
||||
raise UserError(f"表头行 {header_row} 存在重复列名: '{name}'")
|
||||
col_map[name] = c
|
||||
if not col_map:
|
||||
raise UserError(f"表头行 {header_row} 为空,无法识别列名")
|
||||
return col_map
|
||||
|
||||
|
||||
def find_row(ws, col_map: dict, match: dict, header_row: int) -> int:
|
||||
"""用 match(列名 → 值)找唯一匹配的行号。"""
|
||||
if not isinstance(match, dict) or not match:
|
||||
raise UserError("match 必须是非空对象")
|
||||
|
||||
for k in match:
|
||||
if k not in col_map:
|
||||
raise UserError(
|
||||
f"表头无此列: '{k}'(可用: {', '.join(col_map.keys())})"
|
||||
)
|
||||
|
||||
hits = []
|
||||
for r in range(header_row + 1, ws.max_row + 1):
|
||||
ok = True
|
||||
for col_name, want in match.items():
|
||||
v = ws.cell(r, col_map[col_name]).value
|
||||
if not value_eq(v, want):
|
||||
ok = False
|
||||
break
|
||||
if ok:
|
||||
hits.append(r)
|
||||
|
||||
if not hits:
|
||||
raise UserError(f"找不到匹配行: {match}")
|
||||
if len(hits) > 1:
|
||||
raise UserError(f"匹配到 {len(hits)} 行,需增加条件: {match}")
|
||||
return hits[0]
|
||||
|
||||
|
||||
def find_col(col_map: dict, name: str) -> int:
|
||||
if name not in col_map:
|
||||
raise UserError(
|
||||
f"表头无此列: '{name}'(可用: {', '.join(col_map.keys())})"
|
||||
)
|
||||
return col_map[name]
|
||||
@@ -0,0 +1,697 @@
|
||||
"""sheet-edit 的各个 op 实现。"""
|
||||
import datetime
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import openpyxl
|
||||
from openpyxl.utils import get_column_letter
|
||||
from openpyxl.cell.cell import MergedCell
|
||||
from openpyxl.worksheet.cell_range import CellRange, MultiCellRange
|
||||
from openpyxl.worksheet.formula import ArrayFormula
|
||||
|
||||
from . import UserError, convert, formulas, locate
|
||||
|
||||
# inspect 返回的公式清单条数上限(大表防爆 token)
|
||||
MAX_FORMULAS = 500
|
||||
|
||||
|
||||
def _json_safe(v):
|
||||
"""单元格值 → JSON 可序列化形态。"""
|
||||
if isinstance(v, ArrayFormula):
|
||||
return {'formula': v.text}
|
||||
if isinstance(v, datetime.datetime):
|
||||
return v.strftime('%Y-%m-%d %H:%M:%S') if (v.hour or v.minute or v.second) else v.strftime('%Y-%m-%d')
|
||||
if isinstance(v, (datetime.date, datetime.time)):
|
||||
return v.isoformat()
|
||||
if isinstance(v, datetime.timedelta):
|
||||
return str(v)
|
||||
return v
|
||||
|
||||
|
||||
def _cell_text(v):
|
||||
"""公式统一成字符串形态(ArrayFormula → 其文本),供内部比较用。"""
|
||||
return v.text if isinstance(v, ArrayFormula) else v
|
||||
|
||||
|
||||
def _is_formula_val(v):
|
||||
return locate.is_formula(v) or isinstance(v, ArrayFormula)
|
||||
|
||||
|
||||
# ============ inspect ============
|
||||
|
||||
def inspect(args):
|
||||
file = _req_file(args)
|
||||
header_row = _int(args, 'header_row', 1)
|
||||
limit = _int(args, 'limit', 50)
|
||||
sheet_filter = args.get('sheet')
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
xlsx = convert.to_workbook(file, Path(td))
|
||||
wb = openpyxl.load_workbook(xlsx, data_only=False)
|
||||
|
||||
sheets = []
|
||||
found = False
|
||||
for name in wb.sheetnames:
|
||||
if sheet_filter and name != sheet_filter:
|
||||
continue
|
||||
found = True
|
||||
ws = wb[name]
|
||||
sheets.append(_sheet_info(ws, name, header_row, limit))
|
||||
|
||||
if sheet_filter and not found:
|
||||
raise UserError(
|
||||
f"sheet 不存在: {sheet_filter}(可用: {', '.join(wb.sheetnames)})"
|
||||
)
|
||||
|
||||
return {'ok': True, 'sheets': sheets}
|
||||
|
||||
|
||||
def _sheet_info(ws, name, header_row, limit):
|
||||
info = {
|
||||
'name': name,
|
||||
'rows': ws.max_row,
|
||||
'cols': ws.max_column,
|
||||
'header_row': header_row,
|
||||
'headers': [
|
||||
_json_safe(ws.cell(header_row, c).value)
|
||||
for c in range(1, ws.max_column + 1)
|
||||
],
|
||||
'preview': [],
|
||||
'formulas': [],
|
||||
'formulas_truncated': False,
|
||||
'merged': [str(r) for r in ws.merged_cells.ranges],
|
||||
'truncated': False,
|
||||
}
|
||||
for row in ws.iter_rows():
|
||||
for cell in row:
|
||||
v = cell.value
|
||||
if _is_formula_val(v):
|
||||
if len(info['formulas']) < MAX_FORMULAS:
|
||||
info['formulas'].append({'cell': cell.coordinate, 'formula': _cell_text(v)})
|
||||
else:
|
||||
info['formulas_truncated'] = True
|
||||
end = min(header_row + limit, ws.max_row)
|
||||
for r in range(header_row + 1, end + 1):
|
||||
row_data = []
|
||||
for c in range(1, ws.max_column + 1):
|
||||
v = ws.cell(r, c).value
|
||||
row_data.append({'formula': _cell_text(v)} if _is_formula_val(v) else _json_safe(v))
|
||||
info['preview'].append(row_data)
|
||||
info['truncated'] = ws.max_row > end
|
||||
return info
|
||||
|
||||
|
||||
# ============ apply ============
|
||||
|
||||
def apply(args):
|
||||
file = _req_file(args)
|
||||
header_row = _int(args, 'header_row', 1)
|
||||
changes = args.get('changes')
|
||||
if not isinstance(changes, list) or not changes:
|
||||
raise UserError("changes 必须是非空数组")
|
||||
|
||||
original_ext = convert.check_supported(file)
|
||||
out_path = _out_path(file, args.get('output'))
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
xlsx = convert.to_workbook(file, Path(td))
|
||||
wb = openpyxl.load_workbook(xlsx, data_only=False)
|
||||
|
||||
plan = []
|
||||
for ch in changes:
|
||||
plan.extend(_resolve_change(wb, ch, header_row))
|
||||
|
||||
for item in plan:
|
||||
if not locate.value_eq(item['expected_old'], item['actual_old']):
|
||||
raise UserError(
|
||||
f"旧值不匹配: {item['sheet']} 第 {item['row']} 行 "
|
||||
f"'{item['col_name']}': 期望 {item['expected_old']!r}, "
|
||||
f"实际 {_json_safe(item['actual_old'])!r}"
|
||||
)
|
||||
|
||||
before = _snapshot(wb)
|
||||
|
||||
for item in plan:
|
||||
ws = wb[item['sheet']]
|
||||
_assert_writable(ws, item['row'], item['col'])
|
||||
ws.cell(item['row'], item['col']).value = item['new']
|
||||
|
||||
_save(wb, xlsx)
|
||||
convert.from_workbook(xlsx, out_path, original_ext)
|
||||
try:
|
||||
_verify_apply(out_path, before, plan)
|
||||
except Exception:
|
||||
_drop(out_path)
|
||||
raise
|
||||
|
||||
return {
|
||||
'ok': True,
|
||||
'output': out_path.name,
|
||||
'changes': [
|
||||
{
|
||||
'sheet': it['sheet'],
|
||||
'row': it['row'],
|
||||
'col_name': it['col_name'],
|
||||
'old': _json_safe(it['actual_old']),
|
||||
'new': _json_safe(it['new']),
|
||||
'match': it['match'],
|
||||
}
|
||||
for it in plan
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _resolve_change(wb, ch, header_row):
|
||||
sheet = ch.get('sheet')
|
||||
if not sheet:
|
||||
raise UserError("change 缺少 sheet")
|
||||
if sheet not in wb.sheetnames:
|
||||
raise UserError(
|
||||
f"sheet 不存在: {sheet}(可用: {', '.join(wb.sheetnames)})"
|
||||
)
|
||||
match = ch.get('match') or {}
|
||||
set_spec = ch.get('set') or {}
|
||||
if not isinstance(set_spec, dict) or not set_spec:
|
||||
raise UserError("change.set 必须是非空对象")
|
||||
|
||||
ws = wb[sheet]
|
||||
col_map = locate.build_col_map(ws, header_row)
|
||||
row = locate.find_row(ws, col_map, match, header_row)
|
||||
|
||||
items = []
|
||||
for col_name, spec in set_spec.items():
|
||||
if not isinstance(spec, dict) or 'old' not in spec or 'new' not in spec:
|
||||
raise UserError(
|
||||
f"set['{col_name}'] 必须是 {{\"old\": ..., \"new\": ...}} 格式"
|
||||
)
|
||||
col = locate.find_col(col_map, col_name)
|
||||
actual = ws.cell(row, col).value
|
||||
if isinstance(actual, ArrayFormula):
|
||||
raise UserError(
|
||||
f"{sheet}!{get_column_letter(col)}{row} 是数组公式,"
|
||||
"本工具不支持修改(请在 Excel/WPS 手工处理)"
|
||||
)
|
||||
new = spec['new']
|
||||
if isinstance(new, (dict, list)):
|
||||
raise UserError(f"set['{col_name}'].new 只能是数字/字符串/布尔/null,收到 {new!r}")
|
||||
items.append({
|
||||
'sheet': sheet,
|
||||
'row': row,
|
||||
'col': col,
|
||||
'col_name': col_name,
|
||||
'match': dict(match),
|
||||
'expected_old': spec['old'],
|
||||
'actual_old': actual,
|
||||
'new': new,
|
||||
})
|
||||
return items
|
||||
|
||||
|
||||
def _verify_apply(out_path, before, plan):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
xlsx = convert.to_workbook(out_path, Path(td))
|
||||
wb = openpyxl.load_workbook(xlsx, data_only=False)
|
||||
|
||||
for item in plan:
|
||||
v = wb[item['sheet']].cell(item['row'], item['col']).value
|
||||
if not locate.value_eq(v, item['new']):
|
||||
raise UserError(
|
||||
f"校验失败: {item['sheet']} 第 {item['row']} 行 "
|
||||
f"'{item['col_name']}' 应为 {item['new']!r}, 实际 {v!r}"
|
||||
)
|
||||
|
||||
targets = {(it['sheet'], it['row'], it['col']) for it in plan}
|
||||
diffs = []
|
||||
for name in wb.sheetnames:
|
||||
ws = wb[name]
|
||||
before_sheet = before.get(name, {})
|
||||
for r in range(1, ws.max_row + 1):
|
||||
for c in range(1, ws.max_column + 1):
|
||||
if (name, r, c) in targets:
|
||||
continue
|
||||
v = _cell_text(ws.cell(r, c).value)
|
||||
if locate.is_formula(v):
|
||||
continue # apply 不动公式;公式若有变化在下面单独盯
|
||||
if (r, c) not in before_sheet:
|
||||
if _notempty(v):
|
||||
diffs.append(f"{name} ({r},{c}): 新增 {v!r}")
|
||||
continue
|
||||
if not locate.value_eq(before_sheet[(r, c)], v):
|
||||
diffs.append(
|
||||
f"{name} ({r,c}): {before_sheet[(r,c)]!r} → {v!r}"
|
||||
)
|
||||
# 公式原文必须一字不变(apply 语义:只改值,不动公式)
|
||||
for (r, c), v0 in before_sheet.items():
|
||||
if not locate.is_formula(v0):
|
||||
continue
|
||||
if (name, r, c) in targets:
|
||||
continue
|
||||
v1 = _cell_text(ws.cell(r, c).value)
|
||||
if v1 != v0:
|
||||
diffs.append(f"{name} 公式被改动 ({r},{c}): {v0!r} → {v1!r}")
|
||||
if diffs:
|
||||
raise UserError(
|
||||
"校验失败: 非目标单元格发生变化:\n " + "\n ".join(diffs[:20])
|
||||
)
|
||||
|
||||
|
||||
# ============ insert_rows / delete_rows ============
|
||||
|
||||
def insert_rows(args):
|
||||
file = _req_file(args)
|
||||
sheet = _req_sheet(args)
|
||||
count = _pos_int(args, 'count', 1)
|
||||
header_row = _int(args, 'header_row', 1)
|
||||
fill = args.get('fill') or {}
|
||||
after_match = args.get('after_match') or {}
|
||||
if fill and not isinstance(fill, dict):
|
||||
raise UserError("fill 必须是对象")
|
||||
|
||||
original_ext = convert.check_supported(file)
|
||||
out_path = _out_path(file, args.get('output'))
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
xlsx = convert.to_workbook(file, Path(td))
|
||||
wb = openpyxl.load_workbook(xlsx, data_only=False)
|
||||
_check_sheet(wb, sheet)
|
||||
|
||||
ws = wb[sheet]
|
||||
col_map = locate.build_col_map(ws, header_row)
|
||||
anchor = locate.find_row(ws, col_map, after_match, header_row)
|
||||
insert_at = anchor + 1
|
||||
|
||||
fill_cells = {}
|
||||
for col_name, value in fill.items():
|
||||
fill_cells[col_name] = (locate.find_col(col_map, col_name), value)
|
||||
|
||||
before = _snapshot(wb)
|
||||
_adjust_formulas(wb, sheet, 'row', insert_at, count, delete=False)
|
||||
ws.insert_rows(insert_at, count)
|
||||
_shift_merged(ws, 'row', insert_at, count, delete=False)
|
||||
_materialize(ws, insert_at, insert_at + count - 1, 'row')
|
||||
expected_new = {}
|
||||
for col_name, (c, value) in fill_cells.items():
|
||||
for r in range(insert_at, insert_at + count):
|
||||
_assert_writable(ws, r, c, where=f"fill 列 '{col_name}' 新行")
|
||||
ws.cell(r, c).value = value
|
||||
expected_new[(r, c)] = value
|
||||
|
||||
_save(wb, xlsx)
|
||||
convert.from_workbook(xlsx, out_path, original_ext)
|
||||
try:
|
||||
_verify_struct(out_path, before, sheet, 'row', insert_at, count, False, expected_new)
|
||||
except Exception:
|
||||
_drop(out_path)
|
||||
raise
|
||||
|
||||
return {
|
||||
'ok': True,
|
||||
'output': out_path.name,
|
||||
'sheet': sheet,
|
||||
'inserted_at': insert_at,
|
||||
'count': count,
|
||||
}
|
||||
|
||||
|
||||
def delete_rows(args):
|
||||
file = _req_file(args)
|
||||
sheet = _req_sheet(args)
|
||||
count = _pos_int(args, 'count', 1)
|
||||
header_row = _int(args, 'header_row', 1)
|
||||
match = args.get('match') or {}
|
||||
|
||||
original_ext = convert.check_supported(file)
|
||||
out_path = _out_path(file, args.get('output'))
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
xlsx = convert.to_workbook(file, Path(td))
|
||||
wb = openpyxl.load_workbook(xlsx, data_only=False)
|
||||
_check_sheet(wb, sheet)
|
||||
|
||||
ws = wb[sheet]
|
||||
col_map = locate.build_col_map(ws, header_row)
|
||||
start = locate.find_row(ws, col_map, match, header_row)
|
||||
|
||||
before = _snapshot(wb)
|
||||
_adjust_formulas(wb, sheet, 'row', start, count, delete=True)
|
||||
ws.delete_rows(start, count)
|
||||
_shift_merged(ws, 'row', start, count, delete=True)
|
||||
|
||||
_save(wb, xlsx)
|
||||
convert.from_workbook(xlsx, out_path, original_ext)
|
||||
try:
|
||||
_verify_struct(out_path, before, sheet, 'row', start, count, True, {})
|
||||
except Exception:
|
||||
_drop(out_path)
|
||||
raise
|
||||
|
||||
return {
|
||||
'ok': True,
|
||||
'output': out_path.name,
|
||||
'sheet': sheet,
|
||||
'deleted_at': start,
|
||||
'count': count,
|
||||
}
|
||||
|
||||
|
||||
# ============ insert_cols / delete_cols ============
|
||||
|
||||
def insert_cols(args):
|
||||
file = _req_file(args)
|
||||
sheet = _req_sheet(args)
|
||||
after = args.get('after')
|
||||
if not after:
|
||||
raise UserError("缺少 after(在此列之后插入)")
|
||||
count = _pos_int(args, 'count', 1)
|
||||
header_row = _int(args, 'header_row', 1)
|
||||
fill_header = args.get('fill_header')
|
||||
if fill_header and count > 1:
|
||||
raise UserError("fill_header 目前只支持 count=1")
|
||||
|
||||
original_ext = convert.check_supported(file)
|
||||
out_path = _out_path(file, args.get('output'))
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
xlsx = convert.to_workbook(file, Path(td))
|
||||
wb = openpyxl.load_workbook(xlsx, data_only=False)
|
||||
_check_sheet(wb, sheet)
|
||||
|
||||
ws = wb[sheet]
|
||||
col_map = locate.build_col_map(ws, header_row)
|
||||
anchor = locate.find_col(col_map, after)
|
||||
insert_at = anchor + 1
|
||||
|
||||
before = _snapshot(wb)
|
||||
_adjust_formulas(wb, sheet, 'col', insert_at, count, delete=False)
|
||||
ws.insert_cols(insert_at, count)
|
||||
_shift_merged(ws, 'col', insert_at, count, delete=False)
|
||||
_materialize(ws, insert_at, insert_at + count - 1, 'col')
|
||||
expected_new = {}
|
||||
if fill_header:
|
||||
_assert_writable(ws, header_row, insert_at, where="fill_header")
|
||||
ws.cell(header_row, insert_at).value = fill_header
|
||||
expected_new[(header_row, insert_at)] = fill_header
|
||||
|
||||
_save(wb, xlsx)
|
||||
convert.from_workbook(xlsx, out_path, original_ext)
|
||||
try:
|
||||
_verify_struct(out_path, before, sheet, 'col', insert_at, count, False, expected_new)
|
||||
except Exception:
|
||||
_drop(out_path)
|
||||
raise
|
||||
|
||||
return {
|
||||
'ok': True,
|
||||
'output': out_path.name,
|
||||
'sheet': sheet,
|
||||
'inserted_at': insert_at,
|
||||
'count': count,
|
||||
}
|
||||
|
||||
|
||||
def delete_cols(args):
|
||||
file = _req_file(args)
|
||||
sheet = _req_sheet(args)
|
||||
col_name = args.get('col')
|
||||
if not col_name:
|
||||
raise UserError("缺少 col(要删除的列名)")
|
||||
count = _pos_int(args, 'count', 1)
|
||||
header_row = _int(args, 'header_row', 1)
|
||||
|
||||
original_ext = convert.check_supported(file)
|
||||
out_path = _out_path(file, args.get('output'))
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
xlsx = convert.to_workbook(file, Path(td))
|
||||
wb = openpyxl.load_workbook(xlsx, data_only=False)
|
||||
_check_sheet(wb, sheet)
|
||||
|
||||
ws = wb[sheet]
|
||||
col_map = locate.build_col_map(ws, header_row)
|
||||
start = locate.find_col(col_map, col_name)
|
||||
|
||||
before = _snapshot(wb)
|
||||
_adjust_formulas(wb, sheet, 'col', start, count, delete=True)
|
||||
ws.delete_cols(start, count)
|
||||
_shift_merged(ws, 'col', start, count, delete=True)
|
||||
|
||||
_save(wb, xlsx)
|
||||
convert.from_workbook(xlsx, out_path, original_ext)
|
||||
try:
|
||||
_verify_struct(out_path, before, sheet, 'col', start, count, True, {})
|
||||
except Exception:
|
||||
_drop(out_path)
|
||||
raise
|
||||
|
||||
return {
|
||||
'ok': True,
|
||||
'output': out_path.name,
|
||||
'sheet': sheet,
|
||||
'deleted_at': start,
|
||||
'count': count,
|
||||
}
|
||||
|
||||
|
||||
# ============ 内部工具 ============
|
||||
|
||||
def _req_file(args) -> Path:
|
||||
f = args.get('file')
|
||||
if not f:
|
||||
raise UserError("缺少 file 参数")
|
||||
p = Path(f)
|
||||
if not p.exists():
|
||||
raise UserError(f"文件不存在: {f}")
|
||||
return p
|
||||
|
||||
|
||||
def _req_sheet(args) -> str:
|
||||
s = args.get('sheet')
|
||||
if not s:
|
||||
raise UserError("缺少 sheet 参数")
|
||||
return s
|
||||
|
||||
|
||||
def _check_sheet(wb, sheet):
|
||||
if sheet not in wb.sheetnames:
|
||||
raise UserError(
|
||||
f"sheet 不存在: {sheet}(可用: {', '.join(wb.sheetnames)})"
|
||||
)
|
||||
|
||||
|
||||
def _int(args, key, default):
|
||||
v = args.get(key)
|
||||
if v is None:
|
||||
return default
|
||||
try:
|
||||
return int(v)
|
||||
except (TypeError, ValueError):
|
||||
raise UserError(f"{key} 必须是整数: {v!r}")
|
||||
|
||||
|
||||
def _pos_int(args, key, default):
|
||||
v = _int(args, key, default)
|
||||
if v < 1:
|
||||
raise UserError(f"{key} 必须 >= 1: {v}")
|
||||
return v
|
||||
|
||||
|
||||
def _out_path(file: Path, output):
|
||||
if output:
|
||||
name = str(output)
|
||||
# 输出名消毒:只允许文件名,防目录越权(会话目录之外不可写)
|
||||
if '/' in name or '\\' in name or name in ('.', '..') or Path(name).name != name:
|
||||
raise UserError(f"output 只能是文件名(不能含路径分隔符或目录): {name!r}")
|
||||
return file.parent / name
|
||||
return file.parent / f"{file.stem}(已改){file.suffix}"
|
||||
|
||||
|
||||
def _assert_writable(ws, r, c, where=None):
|
||||
"""目标格落在合并区域内且不是锚点 → 拒写(openpyxl 写 MergedCell 会裸 AttributeError)。"""
|
||||
for cr in ws.merged_cells.ranges:
|
||||
if cr.min_row <= r <= cr.max_row and cr.min_col <= c <= cr.max_col:
|
||||
if (r, c) != (cr.min_row, cr.min_col):
|
||||
loc = f"{ws.title}!{get_column_letter(c)}{r}"
|
||||
raise UserError(
|
||||
f"{where or loc} 落在合并区域 {cr.coord} 内且不是锚点格,"
|
||||
"请改写到该区域左上角锚点"
|
||||
)
|
||||
return
|
||||
|
||||
|
||||
def _save(wb, xlsx):
|
||||
# openpyxl 保存会丢公式缓存值;置 fullCalcOnLoad 让 Excel/WPS/LibreOffice 打开时全量重算
|
||||
wb.calculation.fullCalcOnLoad = True
|
||||
wb.save(xlsx)
|
||||
|
||||
|
||||
def _drop(path: Path):
|
||||
"""交付校验失败时移除坏产物,兑现「不交付」。"""
|
||||
try:
|
||||
path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _adjust_formulas(wb, target_sheet, axis, at, count, delete):
|
||||
"""全工作簿调整公式:含「其他表引用目标表」的跨表公式;目标表引用他表的不动(同 Excel)。
|
||||
|
||||
数组公式/外部簿引用/结构化引用 → UserError,整体放弃(调用方删产物)。
|
||||
"""
|
||||
for ws in wb.worksheets:
|
||||
for row in ws.iter_rows():
|
||||
for cell in row:
|
||||
v = cell.value
|
||||
if isinstance(v, ArrayFormula):
|
||||
raise UserError(
|
||||
f"不支持数组公式({ws.title}!{cell.coordinate}),"
|
||||
"请先在 Excel/WPS 中将其转为普通公式后重试"
|
||||
)
|
||||
if locate.is_formula(v):
|
||||
cell.value = formulas.shift_formula(
|
||||
v, ws.title, target_sheet, axis, at, count, delete)
|
||||
|
||||
|
||||
def _shift_merged(ws, axis, at, count, delete):
|
||||
"""合并区域随插删移动(openpyxl 原生不管 merged_cells)。
|
||||
|
||||
插入:边界 >= at 后移 → 跨界插入时区域自动扩大(同 Excel)。
|
||||
删除:区域整体落在删除带内 → 收缩到带前;完全被删 → 消失。
|
||||
部分重叠(一头在带内、另一头在外)Excel 语义含糊 → 直接拒绝。
|
||||
"""
|
||||
def fully_in(v):
|
||||
return at <= v < at + count
|
||||
|
||||
def mv(v):
|
||||
if not delete:
|
||||
return v + count if v >= at else v
|
||||
if v < at:
|
||||
return v
|
||||
if v < at + count:
|
||||
return at - 1
|
||||
return v - count
|
||||
|
||||
moved = []
|
||||
for cr in ws.merged_cells.ranges:
|
||||
r1, r2, c1, c2 = cr.min_row, cr.max_row, cr.min_col, cr.max_col
|
||||
if delete:
|
||||
if axis == 'row' and fully_in(r1) != fully_in(r2):
|
||||
raise UserError(f"不支持删除跨越合并区域 {cr.coord} 边界的行(Excel 行为无法推断)")
|
||||
if axis == 'col' and fully_in(c1) != fully_in(c2):
|
||||
raise UserError(f"不支持删除跨越合并区域 {cr.coord} 边界的列(Excel 行为无法推断)")
|
||||
nr1, nr2, nc1, nc2 = (mv(r1), mv(r2), c1, c2) if axis == 'row' else (r1, r2, mv(c1), mv(c2))
|
||||
if nr1 == nr2 and nc1 == nc2:
|
||||
continue # 区域整体消失
|
||||
moved.append(str(CellRange(min_col=nc1, min_row=nr1, max_col=nc2, max_row=nr2)))
|
||||
ws.merged_cells = MultiCellRange(ranges=set(moved))
|
||||
|
||||
|
||||
def _materialize(ws, a, b, axis):
|
||||
"""把新插的空行/空列注册进单元格表(否则 openpyxl 不扩大 dimension,csv 回写会丢行)。"""
|
||||
if axis == 'row':
|
||||
for r in range(a, b + 1):
|
||||
ws.cell(r, 1)
|
||||
else:
|
||||
for c in range(a, b + 1):
|
||||
ws.cell(1, c)
|
||||
|
||||
|
||||
def _snapshot(wb):
|
||||
"""记录所有单元格(含公式原文),供插删后的结构化自检。"""
|
||||
snap = {}
|
||||
for ws in wb.worksheets:
|
||||
d = {}
|
||||
for row in ws.iter_rows():
|
||||
for cell in row:
|
||||
if cell.value is not None:
|
||||
d[(cell.row, cell.column)] = _cell_text(cell.value)
|
||||
snap[ws.title] = d
|
||||
return snap
|
||||
|
||||
|
||||
def _map_axis(v, at, count, delete):
|
||||
"""旧坐标 → 新坐标;None 表示落在被删除带内。"""
|
||||
if not delete:
|
||||
return v + count if v >= at else v
|
||||
if v < at:
|
||||
return v
|
||||
if v < at + count:
|
||||
return None
|
||||
return v - count
|
||||
|
||||
|
||||
def _notempty(v):
|
||||
return v is not None and v != ''
|
||||
|
||||
|
||||
def _cmp_norm(v):
|
||||
"""比较归一:csv 往返的空串视同空。"""
|
||||
return None if v == '' else v
|
||||
|
||||
|
||||
def _verify_struct(out_path, before, sheet, axis, at, count, delete, expected_new):
|
||||
"""插删自检:目标表尺寸正确;旧格按坐标映射逐一存在(公式等于预期调整结果);
|
||||
非操作表尺寸不变、内容仅允许「引用目标表的公式」发生调整;新带区域除 fill 外为空。"""
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
xlsx = convert.to_workbook(out_path, Path(td))
|
||||
wb = openpyxl.load_workbook(xlsx, data_only=False)
|
||||
|
||||
diffs = []
|
||||
for ws in wb.worksheets:
|
||||
is_target = ws.title == sheet
|
||||
bf = before.get(ws.title, {})
|
||||
rows_b = max((r for r, _ in bf), default=0)
|
||||
cols_b = max((c for _, c in bf), default=0)
|
||||
|
||||
if is_target:
|
||||
exp_rows = _map_bounds(rows_b, axis, 'row', at, count, delete)
|
||||
exp_cols = _map_bounds(cols_b, axis, 'col', at, count, delete)
|
||||
if ws.max_row != exp_rows:
|
||||
diffs.append(f"{ws.title}: 行数应为 {exp_rows} 实际 {ws.max_row}")
|
||||
if ws.max_column != exp_cols:
|
||||
diffs.append(f"{ws.title}: 列数应为 {exp_cols} 实际 {ws.max_column}")
|
||||
else:
|
||||
if ws.max_row != rows_b or ws.max_column != cols_b:
|
||||
diffs.append(
|
||||
f"{ws.title}: 非操作表尺寸被波及 {rows_b}x{cols_b} → {ws.max_row}x{ws.max_column}")
|
||||
|
||||
for (r, c), v in bf.items():
|
||||
nr, nc = r, c
|
||||
if is_target:
|
||||
nr = _map_axis(r, at, count, delete) if axis == 'row' else r
|
||||
nc = _map_axis(c, at, count, delete) if axis == 'col' else c
|
||||
if nr is None or nc is None:
|
||||
continue
|
||||
actual = _cmp_norm(_cell_text(ws.cell(nr, nc).value))
|
||||
expected = v
|
||||
if locate.is_formula(v):
|
||||
expected = formulas.shift_formula(v, ws.title, sheet, axis, at, count, delete)
|
||||
if not locate.value_eq(_cmp_norm(expected), actual):
|
||||
diffs.append(f"{ws.title} ({r},{c})→({nr},{nc}): 期望 {expected!r} 实际 {actual!r}")
|
||||
|
||||
if not delete:
|
||||
ws = wb[sheet]
|
||||
band = range(at, at + count)
|
||||
rows = band if axis == 'row' else range(1, ws.max_row + 1)
|
||||
cols = range(1, ws.max_column + 1) if axis == 'row' else band
|
||||
for r in rows:
|
||||
for c in cols:
|
||||
v = _cmp_norm(_cell_text(ws.cell(r, c).value))
|
||||
if (r, c) in expected_new:
|
||||
if not locate.value_eq(_cmp_norm(expected_new[(r, c)]), v):
|
||||
diffs.append(f"{sheet} fill({r},{c}) 应为 {expected_new[(r, c)]!r} 实际 {v!r}")
|
||||
elif _notempty(v):
|
||||
diffs.append(f"{sheet} 新区域({r},{c}) 应为空 实际 {v!r}")
|
||||
|
||||
if diffs:
|
||||
raise UserError("校验失败: 插删后结构与预期不符:\n " + "\n ".join(diffs[:20]))
|
||||
|
||||
|
||||
def _map_bounds(n, _axis, kind, at, count, delete):
|
||||
"""快照尺寸 → 预期新尺寸(按轴)。"""
|
||||
if kind != _axis:
|
||||
return n
|
||||
if not delete:
|
||||
return n + count
|
||||
if n < at:
|
||||
return n
|
||||
return n - min(count, n - at + 1)
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""sheet-edit 技能入口。接收一个 JSON 参数,分发到对应 op。"""
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from lib import UserError, ops
|
||||
|
||||
|
||||
HANDLERS = {
|
||||
'inspect': ops.inspect,
|
||||
'apply': ops.apply,
|
||||
'insert_rows': ops.insert_rows,
|
||||
'delete_rows': ops.delete_rows,
|
||||
'insert_cols': ops.insert_cols,
|
||||
'delete_cols': ops.delete_cols,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2 or not sys.argv[1].strip():
|
||||
_err("用法: run.py '<json>'")
|
||||
return 1
|
||||
try:
|
||||
args = json.loads(sys.argv[1])
|
||||
except json.JSONDecodeError as e:
|
||||
_err(f"input_args JSON 解析失败: {e}")
|
||||
return 1
|
||||
if not isinstance(args, dict):
|
||||
_err("input_args 必须是 JSON 对象")
|
||||
return 1
|
||||
|
||||
op = args.get('op')
|
||||
handler = HANDLERS.get(op)
|
||||
if not handler:
|
||||
_err(f"未知 op: {op!r}(支持: {', '.join(HANDLERS.keys())})")
|
||||
return 1
|
||||
|
||||
try:
|
||||
result = handler(args)
|
||||
# default=str 兕底:任何漏网的不可序列化值降级为字符串,不让整次运行因输出崩掉
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
|
||||
return 0
|
||||
except UserError as e:
|
||||
_err(str(e))
|
||||
return 1
|
||||
except Exception as e:
|
||||
_err(f"内部错误: {type(e).__name__}: {e}")
|
||||
return 1
|
||||
|
||||
|
||||
def _err(msg):
|
||||
print(json.dumps({'ok': False, 'error': msg}, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user