diff --git a/skills/sheet-edit/SKILL.md b/skills/sheet-edit/SKILL.md index 20cb7d9..2909392 100644 --- a/skills/sheet-edit/SKILL.md +++ b/skills/sheet-edit/SKILL.md @@ -27,7 +27,7 @@ description: 结构化修改表格文件。内容定位(列名 + 值),最 ## 工作流程 -1. `action=inspect` 查看表结构与公式(注意采用返回里的 `suggested_header_row`) +1. `action=inspect` 查看表结构与公式(注意采用返回里的 `suggested_header_row`;若 `multi_level_header` 非 null,列名模式不可用,直接走 `cells` 地址模式) 2. 按需求选择 `action=apply` / `insert_rows` / `delete_rows` / `insert_cols` / `delete_cols` ## inspect @@ -56,6 +56,7 @@ description: 结构化修改表格文件。内容定位(列名 + 值),最 "cols": 7, "header_row": 1, "suggested_header_row": 1, + "multi_level_header": null, "headers": ["序号", "项目", "单位", "数量", "单价", "金额", "备注"], "preview": [ [1, "管道", "米", 100, 18, {"formula": "=D3*E3"}, ""], @@ -74,6 +75,7 @@ description: 结构化修改表格文件。内容定位(列名 + 值),最 要点: - `headers` 是表头行;合并单元格只有首个有值,其余为 `null` - `suggested_header_row` 是自动检测的表头行(中文表格常见「第 1 行合并标题 + 第 2 行真表头」);与你的 `header_row` 不一致时直接采用它继续后续调用,不用自己推断 +- `multi_level_header` 非 null(如 `{"group_row": 2, "column_row": 3}`)= 多级表头(分组行 + 重复子列名行):列名定位必死,改用 `cells` 地址模式,别反复换 `header_row` 重试 - 公式以 `{"formula": "=..."}` 表示 - `preview` 可能被 `limit` 截断;`formulas` 最多列 500 条(超出时 `formulas_truncated: true`) - `merged` 是合并区域列表(如 `["A1:G1"]`) @@ -97,10 +99,28 @@ description: 结构化修改表格文件。内容定位(列名 + 值),最 参数: - `file`(必填) -- `changes`(必填):改动清单 -- `header_row`(可选,默认 1) +- `changes`(必填):改动清单;每项可用 `match+set`(列名定位)或 `cells`(地址定位),二选一 +- `header_row`(可选,默认 1);各 change 可单独带 `header_row` 字段覆盖(多 sheet 表头位置不同时用) - `output`(可选):输出文件名(放原文件同目录;平台预处理成会话目录下的绝对路径也接受),默认原文件名加「(已改)」 +### cells 地址定位(多级表头 / 分组汇总表的正经出口) + +```json +{ + "action": "apply", + "file": "预算表.xlsx", + "changes": [ + {"sheet": "总表", "cells": { + "D4": {"old": 157, "new": 190}, + "F4": {"old": 120, "new": 150} + }} + ] +} +``` + +- 地址从 inspect 的 `preview`(含列坐标提示)/`formulas` 里数出来;允许可选 `$`(`$D$4` 同 `D4`) +- old 校验、合并区防护、全簿逐格自检、LO 重算与列名模式**完全同源**,不是降级通道 + ### 定位 `match` 用列名 + 值定位目标行,可多列组合: @@ -204,6 +224,7 @@ description: 结构化修改表格文件。内容定位(列名 + 值),最 - 改动后自检:目标改动生效、其他内容未变(含公式原文)、文件可打开 - 任一项失败 → 产物自动删除、不交付 - 遇不支持的引用形态(数组公式、外部簿引用、结构化引用)直接报错,绝不半改交付 +- 超出能力的表(多级表头等)用 `cells` 地址模式处理;**禁止绕开本技能用 terminal/脚本手改交付物**——手改没有 old 校验、逐格自检、跨表引用检查与重算门禁,错了没人兜底 ## 边界 @@ -214,7 +235,7 @@ description: 结构化修改表格文件。内容定位(列名 + 值),最 重算失败时自动回退交付「未重算版」并在结果 `recalc` 字段标注 `failed:...`(未重算版仍带「打开时全量重算」标记, Excel/WPS 打开结果一样正确);结果里看到 recalc=failed 时简短告知用户一句即可,不要重试。 - CSV 单元格一律按文本保留(「007」「1.10」不会变成 7/1.1);数字与数字文本在定位比较时互认。 -- 多级表头、复杂合并:可能定位失败,需手工处理。 +- 多级表头(分组行 + 重复子列名,如「新建顶管|数量·单价」):`match/set` 列名定位不支持(子列名不唯一,任何 `header_row` 都无解);`inspect` 会标 `multi_level_header`,请用 `cells` 地址模式 + 从 preview 确认坐标。更深层级(≥3 行表头)同样走 `cells`。 ## 常见错误 @@ -225,3 +246,4 @@ description: 结构化修改表格文件。内容定位(列名 + 值),最 5. **sheet 不存在**:报错会列出可用 sheet 名 6. **写入合并区域非锚点格**:报错提示改用区域左上角锚点 7. **报「不支持数组公式/外部簿引用」**:该表需人工处理,不要反复重试 +8. **报「重复列名 / 检测到多级表头」**:换 `header_row` 重试没有用(子列名天然不唯一),改用 `cells` 地址模式;也不要因此绕开技能去手改文件 diff --git a/skills/sheet-edit/lib/locate.py b/skills/sheet-edit/lib/locate.py index 32a0a3a..5ba0704 100644 --- a/skills/sheet-edit/lib/locate.py +++ b/skills/sheet-edit/lib/locate.py @@ -32,6 +32,35 @@ def detect_header_row(ws, scan=10, col_cap=200) -> int: return best_row +def detect_multi_level(ws, scan=10, col_cap=200): + """检测“分组行 + 重复子列名行”相邻出现的多级表头形态,返回 (分组行, 列名行) 或 None。 + + 判定:相邻两行均全为字符串;上行值唯一且 ≥2 个(分组标题),下行有重复且 ≥3 个、格数多于上行 + (真列名在多组下重复)。只读不写,纯诊断用。""" + max_c = min(ws.max_column, col_cap) + prev = None # (row, 全字符串, 值列表) + for r in range(1, min(scan, ws.max_row) + 1): + vals = [] + ok = True + for c in range(1, max_c + 1): + v = ws.cell(r, c).value + if v is None or v == '': + continue + if isinstance(v, str) and not v.startswith('='): + vals.append(v.strip()) + else: + ok = False + break + if prev is not None and ok and prev[1] and prev[2]: + pu, cu = prev[2], vals + if (len(pu) >= 2 and len(set(pu)) == len(pu) + and len(cu) >= 3 and len(set(cu)) != len(cu) + and len(cu) > len(pu)): + return (prev[0], r) + prev = (r, ok, vals) + return None + + def value_eq(a, b) -> bool: if a is None and b is None: return True @@ -57,6 +86,13 @@ def build_col_map(ws, header_row: int) -> dict: if not name: continue if name in col_map: + ml = detect_multi_level(ws) + if ml: + raise UserError( + f"表头行 {header_row} 存在重复列名('{name}'),且检测到多级表头" + f"(第 {ml[0]} 行分组、第 {ml[1]} 行子列名):列名模式无法唯一定位," + "请从 inspect 的 preview/formulas 确认目标坐标后改用 change.cells 地址模式" + ) raise UserError(f"表头行 {header_row} 存在重复列名: '{name}'") col_map[name] = c if not col_map: diff --git a/skills/sheet-edit/lib/ops.py b/skills/sheet-edit/lib/ops.py index b9bf6cf..18b12f1 100644 --- a/skills/sheet-edit/lib/ops.py +++ b/skills/sheet-edit/lib/ops.py @@ -1,12 +1,12 @@ """sheet-edit 的各个 op 实现。""" import datetime +import re import shutil import tempfile from pathlib import Path import openpyxl -from openpyxl.utils import get_column_letter -from openpyxl.cell.cell import MergedCell +from openpyxl.utils import column_index_from_string, get_column_letter from openpyxl.worksheet.cell_range import CellRange, MultiCellRange from openpyxl.worksheet.formula import ArrayFormula @@ -74,6 +74,7 @@ def _sheet_info(ws, name, header_row, limit): 'cols': ws.max_column, 'header_row': header_row, 'suggested_header_row': locate.detect_header_row(ws), + 'multi_level_header': None, 'headers': [ _json_safe(ws.cell(header_row, c).value) for c in range(1, ws.max_column + 1) @@ -84,6 +85,9 @@ def _sheet_info(ws, name, header_row, limit): 'merged': [str(r) for r in ws.merged_cells.ranges], 'truncated': False, } + ml = locate.detect_multi_level(ws) + if ml: + info['multi_level_header'] = {'group_row': ml[0], 'column_row': ml[1]} for row in ws.iter_rows(): for cell in row: v = cell.value @@ -173,44 +177,79 @@ def _resolve_change(wb, ch, header_row): 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 必须是非空对象") - + hr = _int(ch, 'header_row', header_row) # change 级可覆盖全局 header_row ws = wb[sheet] - col_map = locate.build_col_map(ws, header_row) - row = locate.find_row(ws, col_map, match, header_row) + + set_spec = ch.get('set') + cells_spec = ch.get('cells') + if set_spec is not None and cells_spec is not None: + raise UserError("change 只能二选一:match+set(列名定位)或 cells(地址定位)") + if cells_spec is not None: + return _resolve_cells(ws, sheet, cells_spec) + + match = ch.get('match') or {} + if not isinstance(set_spec, dict) or not set_spec: + raise UserError("change.set 必须是非空对象(多级表头等无法按列名定位的表改用 change.cells)") + + ml = locate.detect_multi_level(ws) + if ml and hr == ml[0]: + raise UserError( + f"检测到多级表头(第 {ml[0]} 行分组、第 {ml[1]} 行子列名):列名模式无法唯一定位," + "请从 inspect 的 preview/formulas 确认目标坐标后改用 change.cells 地址模式" + ) + col_map = locate.build_col_map(ws, hr) + row = locate.find_row(ws, col_map, match, hr) 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, - }) + items.append(_mk_item(ws, sheet, row, col, col_name, spec, dict(match))) return items +_ADDR_RE = re.compile(r'^\$?([A-Za-z]{1,3})\$?(\d{1,7})$') + + +def _resolve_cells(ws, sheet, cells_spec): + """地址模式:cells = {"C5": {"old": ..., "new": ...}, ...}。多级表头等列名不可用场景的正经出口, + old 校验/合并区防护/全簿自检/重算与列名模式完全同源。""" + if not isinstance(cells_spec, dict) or not cells_spec: + raise UserError("change.cells 必须是非空对象:地址 → {\"old\": ..., \"new\": ...}") + items = [] + for addr, spec in cells_spec.items(): + m = _ADDR_RE.match(str(addr).strip()) + if not m: + raise UserError(f"非法单元格地址: {addr!r}(形如 C5,允许可选 $ 绝对符)") + col = column_index_from_string(m.group(1).upper()) + row = int(m.group(2)) + items.append(_mk_item(ws, sheet, row, col, str(addr).strip().upper(), spec, {})) + return items + + +def _mk_item(ws, sheet, row, col, label, spec, match_info): + if not isinstance(spec, dict) or 'old' not in spec or 'new' not in spec: + raise UserError(f"'{label}' 的设值必须是 {{\"old\": ..., \"new\": ...}} 格式") + 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"'{label}'.new 只能是数字/字符串/布尔/null,收到 {new!r}") + return { + 'sheet': sheet, + 'row': row, + 'col': col, + 'col_name': label, + 'match': match_info, + 'expected_old': spec['old'], + 'actual_old': actual, + 'new': new, + } + + def _verify_apply(out_path, before, plan): with tempfile.TemporaryDirectory() as td: xlsx = convert.to_workbook(out_path, Path(td))