remove sheet skill
This commit is contained in:
@@ -1,251 +0,0 @@
|
|||||||
---
|
|
||||||
name: sheet
|
|
||||||
description: 表格文件(xls/xlsx/csv/ods)的读取与安全修改。自带原文校验、全簿逐格自检、公式引用调整与自动重算。不用于新建工作簿,不用于生成图表
|
|
||||||
required: true
|
|
||||||
---
|
|
||||||
|
|
||||||
# sheet
|
|
||||||
|
|
||||||
## 调用形式(重要)
|
|
||||||
|
|
||||||
本技能通过 `skill` 工具执行,完整调用是:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{"op": "run", "name": "sheet", "input_args": {"action": "inspect", "file": "预算表.xlsx"}}
|
|
||||||
```
|
|
||||||
|
|
||||||
外层 `op`(固定为 run)属于 skill 工具;**下文所有 JSON 示例都是 `input_args` 的内容**,其动作键是 `action`,不要与外层 `op` 混淆。
|
|
||||||
|
|
||||||
## 何时使用
|
|
||||||
|
|
||||||
- 修改表格文件中的单元格值或公式
|
|
||||||
- 插入、删除行或列
|
|
||||||
- 按内容定位目标行/列
|
|
||||||
|
|
||||||
支持格式:`.xls`、`.xlsx`、`.csv`、`.ods`。
|
|
||||||
|
|
||||||
不适用:新建工作簿、生成图表、执行宏。
|
|
||||||
|
|
||||||
## 工作流程
|
|
||||||
|
|
||||||
1. `action=inspect` 查看表结构与公式(注意采用返回里的 `suggested_header_row`;若 `multi_level_header` 非 null,列名模式不可用,直接走 `cells` 地址模式)
|
|
||||||
2. 按需求选择 `action=apply` / `insert_rows` / `delete_rows` / `insert_cols` / `delete_cols`
|
|
||||||
|
|
||||||
## inspect
|
|
||||||
|
|
||||||
读取表结构、单元格值、公式。
|
|
||||||
|
|
||||||
```json
|
|
||||||
{"action": "inspect", "file": "预算表.xlsx"}
|
|
||||||
```
|
|
||||||
|
|
||||||
参数:
|
|
||||||
- `file`(必填):相对任务目录的路径
|
|
||||||
- `sheet`(可选):只查指定 sheet
|
|
||||||
- `limit`(可选):每个 sheet 预览行数,默认 50
|
|
||||||
- `header_row`(可选):表头行号,默认 1
|
|
||||||
|
|
||||||
返回示例:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"ok": true,
|
|
||||||
"sheets": [
|
|
||||||
{
|
|
||||||
"name": "明细",
|
|
||||||
"rows": 10,
|
|
||||||
"cols": 7,
|
|
||||||
"header_row": 1,
|
|
||||||
"suggested_header_row": 1,
|
|
||||||
"multi_level_header": null,
|
|
||||||
"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`
|
|
||||||
- `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"]`)
|
|
||||||
- `truncated` 为 `true` 时预览被截断,改动仍可命中整张表
|
|
||||||
|
|
||||||
## apply(改值/改公式)
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"action": "apply",
|
|
||||||
"file": "预算表.xlsx",
|
|
||||||
"changes": [
|
|
||||||
{
|
|
||||||
"sheet": "明细",
|
|
||||||
"match": {"项目": "顶管"},
|
|
||||||
"set": {"单价": {"old": 157, "new": 180}}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
参数:
|
|
||||||
- `file`(必填)
|
|
||||||
- `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},
|
|
||||||
"H4": {"new": "=D4*0.9"}
|
|
||||||
}}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- 地址从 inspect 的 `preview`(含列坐标提示)/`formulas` 里数出来;允许可选 `$`(`$D$4` 同 `D4`)
|
|
||||||
- 每个地址的 `old` 同样可选(省略 = 空格断言),与 `set` 语义一致
|
|
||||||
- old 校验、合并区防护、全簿逐格自检、LO 重算与列名模式**完全同源**,不是降级通道
|
|
||||||
|
|
||||||
### 定位
|
|
||||||
|
|
||||||
`match` 用列名 + 值定位目标行,可多列组合:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{"match": {"项目": "顶管", "单位": "米"}}
|
|
||||||
```
|
|
||||||
|
|
||||||
`set` 指定要改的列和新旧值:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{"set": {"单价": {"old": 157, "new": 180}}}
|
|
||||||
```
|
|
||||||
|
|
||||||
`old` 可省:**省略 = 断言目标格当前为空再写入**(填空/补列/补公式场景);改已有值必须给 `old`,不一致则整体报错、不做任何改动。
|
|
||||||
|
|
||||||
### 改公式
|
|
||||||
|
|
||||||
`new` 以 `=` 开头即为公式;`old` 用字符串精确匹配:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{"set": {"金额": {"old": "=D3*E3", "new": "=D3*E3*1.1"}}}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 一次改多处
|
|
||||||
|
|
||||||
`changes` 可包含多项,跨 sheet 也可以。
|
|
||||||
|
|
||||||
## insert_rows / delete_rows
|
|
||||||
|
|
||||||
**insert_rows**:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"action": "insert_rows",
|
|
||||||
"file": "预算表.xlsx",
|
|
||||||
"sheet": "明细",
|
|
||||||
"after_match": {"项目": "顶管"},
|
|
||||||
"count": 1,
|
|
||||||
"fill": {"序号": 3, "项目": "新增项", "单位": "米", "数量": 20, "单价": 100, "金额": "=D4*E4"}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- `after_match`:在此行之后插入(用列名 + 值定位)
|
|
||||||
- `count`:插入行数,默认 1
|
|
||||||
- `fill`:可选,为新行填充值(公式按新行实际行号自己写好);以 `=` 开头视为公式
|
|
||||||
|
|
||||||
**delete_rows**:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"action": "delete_rows",
|
|
||||||
"file": "预算表.xlsx",
|
|
||||||
"sheet": "明细",
|
|
||||||
"match": {"项目": "顶管"},
|
|
||||||
"count": 1
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- `match`:要删除的行
|
|
||||||
- `count`:删除行数,默认 1
|
|
||||||
|
|
||||||
行插入/删除会**自动调整公式引用**(含其他工作表中引用本表的跨表公式,同 Excel);合并单元格同步移动,区域内插行会自动扩大区域。
|
|
||||||
|
|
||||||
## insert_cols / delete_cols
|
|
||||||
|
|
||||||
**insert_cols**:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"action": "insert_cols",
|
|
||||||
"file": "预算表.xlsx",
|
|
||||||
"sheet": "明细",
|
|
||||||
"after": "单价",
|
|
||||||
"count": 1,
|
|
||||||
"fill_header": "折扣"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- `after`:在此列之后插入(用列名定位)
|
|
||||||
- `fill_header`:可选,新列的表头
|
|
||||||
|
|
||||||
**delete_cols**:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"action": "delete_cols",
|
|
||||||
"file": "预算表.xlsx",
|
|
||||||
"sheet": "明细",
|
|
||||||
"col": "备注",
|
|
||||||
"count": 1
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
列插入/删除同样会**自动调整公式引用**。
|
|
||||||
|
|
||||||
## 硬约束
|
|
||||||
|
|
||||||
- 只改清单里指定的位置
|
|
||||||
- 改动前校验 `old`(set)或 `match` 唯一性
|
|
||||||
- 改动后自检:目标改动生效、其他内容未变(含公式原文)、文件可打开
|
|
||||||
- 任一项失败 → 产物自动删除、不交付
|
|
||||||
- 遇不支持的引用形态(数组公式、外部簿引用、结构化引用)直接报错,绝不半改交付
|
|
||||||
- 超出能力的表(多级表头等)用 `cells` 地址模式处理;**禁止绕开本技能用 terminal/脚本手改交付物**——手改没有 old 校验、逐格自检、跨表引用检查与重算门禁,错了没人兜底
|
|
||||||
|
|
||||||
## 边界
|
|
||||||
|
|
||||||
- 公式调整范围:目标表内引用、他表→目标表的跨表引用都会改;目标表→他表的引用不动(同 Excel)。
|
|
||||||
被删区域端点的区间按 Excel 语义收缩;命名范围(Tax2023 之类)不改写,引用它们的结果可能错位,需人工核对。
|
|
||||||
- 删除跨越合并区域边界的行/列会被拒绝(行为无法推断),改为整块删或先拆合并。
|
|
||||||
- 产物交付前已自动重算:LibreOffice 对 xlsx/xls/ods 求值并把结果写入公式缓存,可直接进预览/转 PDF/脚本读取;
|
|
||||||
重算失败时自动回退交付「未重算版」并在结果 `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`。
|
|
||||||
|
|
||||||
## 常见错误
|
|
||||||
|
|
||||||
1. **match 不唯一**:多行满足条件,补充更多列条件
|
|
||||||
2. **old 不匹配**:定位错了或数据已变,重新 inspect
|
|
||||||
3. **表头不在第 1 行(标题行+表头行结构极常见)**:看 inspect 的 `suggested_header_row`;apply/insert/delete 若把标题行误当表头,报错信息里会直接给出建议行号,按其重试即可
|
|
||||||
4. **列名不存在**:报错会列出可用列名
|
|
||||||
5. **sheet 不存在**:报错会列出可用 sheet 名
|
|
||||||
6. **写入合并区域非锚点格**:报错提示改用区域左上角锚点
|
|
||||||
7. **报「不支持数组公式/外部簿引用」**:该表需人工处理,不要反复重试
|
|
||||||
8. **报「重复列名 / 检测到多级表头」**:换 `header_row` 重试没有用(子列名天然不唯一),改用 `cells` 地址模式;也不要因此绕开技能去手改文件
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
"""sheet 内部库。"""
|
|
||||||
|
|
||||||
|
|
||||||
class UserError(Exception):
|
|
||||||
"""参数或使用错误,以清晰消息返回给调用方。"""
|
|
||||||
pass
|
|
||||||
@@ -1,149 +0,0 @@
|
|||||||
"""文件格式转换:统一用 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 _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', '--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,
|
|
||||||
)
|
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
# 重算适用的二进制/文档格式(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:
|
|
||||||
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})")
|
|
||||||
@@ -1,158 +0,0 @@
|
|||||||
"""调整 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)
|
|
||||||
@@ -1,147 +0,0 @@
|
|||||||
"""内容定位:用列名 + 值找目标行/列。"""
|
|
||||||
from . import UserError
|
|
||||||
|
|
||||||
|
|
||||||
def is_formula(v) -> bool:
|
|
||||||
return isinstance(v, str) and v.startswith('=')
|
|
||||||
|
|
||||||
|
|
||||||
def detect_header_row(ws, scan=10, col_cap=200) -> int:
|
|
||||||
"""扫描前 scan 行猜表头行(只读不写,纯建议用)。
|
|
||||||
|
|
||||||
候选条件:行内非空值 ≥ 2 且全部是普通字符串(排掉单值标题行和含数字/公式的数据行),行内不重复。
|
|
||||||
取非空格数最多的最早候选行;找不到则回退 1。"""
|
|
||||||
best_row, best_cnt = 1, 0
|
|
||||||
max_c = min(ws.max_column, col_cap)
|
|
||||||
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 not ok or len(vals) < 2 or len(set(vals)) != len(vals):
|
|
||||||
continue
|
|
||||||
if len(vals) > best_cnt:
|
|
||||||
best_row, best_cnt = r, len(vals)
|
|
||||||
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
|
|
||||||
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:
|
|
||||||
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:
|
|
||||||
suggest = detect_header_row(ws)
|
|
||||||
extra = f";疑似真实表头在第 {suggest} 行,请传 header_row={suggest} 重试" if suggest != header_row else ''
|
|
||||||
raise UserError(f"表头行 {header_row} 为空,无法识别列名{extra}")
|
|
||||||
if len(col_map) == 1:
|
|
||||||
# 典型现场:第 1 行是横跨全行的合并标题,单值被当成唯一列名
|
|
||||||
suggest = detect_header_row(ws)
|
|
||||||
if suggest != header_row:
|
|
||||||
raise UserError(
|
|
||||||
f"表头行 {header_row} 只解析出 1 列('{next(iter(col_map))}'),像标题行;"
|
|
||||||
f"疑似真实表头在第 {suggest} 行,请传 header_row={suggest} 重试"
|
|
||||||
)
|
|
||||||
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]
|
|
||||||
@@ -1,781 +0,0 @@
|
|||||||
"""sheet 的各个 op 实现。"""
|
|
||||||
import datetime
|
|
||||||
import re
|
|
||||||
import shutil
|
|
||||||
import tempfile
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import openpyxl
|
|
||||||
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
|
|
||||||
|
|
||||||
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,
|
|
||||||
'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)
|
|
||||||
],
|
|
||||||
'preview': [],
|
|
||||||
'formulas': [],
|
|
||||||
'formulas_truncated': False,
|
|
||||||
'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
|
|
||||||
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:
|
|
||||||
# csv 往返的空串视同空格;省略 old = 空格断言,给了 old = 精确校验
|
|
||||||
act = None if item['actual_old'] == '' else item['actual_old']
|
|
||||||
exp = item['expected_old']
|
|
||||||
if exp is _MISSING:
|
|
||||||
if act is not None:
|
|
||||||
raise UserError(
|
|
||||||
f"目标格非空,拒绝无 old 写入: {item['sheet']} 第 {item['row']} 行 "
|
|
||||||
f"'{item['col_name']}' 当前为 {act!r}(填空应保证目标为空;改已有值必须提供 old)"
|
|
||||||
)
|
|
||||||
elif not locate.value_eq(exp, act):
|
|
||||||
raise UserError(
|
|
||||||
f"旧值不匹配: {item['sheet']} 第 {item['row']} 行 "
|
|
||||||
f"'{item['col_name']}': 期望 {exp!r}, "
|
|
||||||
f"实际 {_json_safe(act)!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
|
|
||||||
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'],
|
|
||||||
'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)})"
|
|
||||||
)
|
|
||||||
hr = _int(ch, 'header_row', header_row) # change 级可覆盖全局 header_row
|
|
||||||
ws = wb[sheet]
|
|
||||||
|
|
||||||
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():
|
|
||||||
col = locate.find_col(col_map, col_name)
|
|
||||||
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})$')
|
|
||||||
|
|
||||||
# set/cells 的 old 缺省哨兵:省略 old = 断言目标格当前为空再写入(填空);改已有值必须显式 old。
|
|
||||||
_MISSING = object()
|
|
||||||
|
|
||||||
|
|
||||||
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 'new' not in spec:
|
|
||||||
raise UserError(f"'{label}' 的设值必须是 {{\"new\": ..., \"old\": 可选...}} 格式")
|
|
||||||
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'] if 'old' in spec else _MISSING,
|
|
||||||
'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))
|
|
||||||
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
|
|
||||||
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,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
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
|
|
||||||
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,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
# ============ 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
|
|
||||||
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,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
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
|
|
||||||
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,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
# ============ 内部工具 ============
|
|
||||||
|
|
||||||
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 name in ('.', '..'):
|
|
||||||
raise UserError(f"output 无效: {name!r}")
|
|
||||||
p = Path(name)
|
|
||||||
# 绝对路径原样用:skills.js 会把 output 这类路径参数预处理成会话目录下的绝对路径,
|
|
||||||
# 拒含分隔符反而把平台惯例变成必死参数;防越权由执行容器自身的会话隔离担责。
|
|
||||||
return p if p.is_absolute() else file.parent / p
|
|
||||||
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 _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)。
|
|
||||||
|
|
||||||
数组公式/外部簿引用/结构化引用 → 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)
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""sheet 技能入口。接收一个 JSON 参数,按其中 action 键分发(旧键名 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
|
|
||||||
|
|
||||||
action = args.get('action') or args.get('op') or 'inspect'
|
|
||||||
handler = HANDLERS.get(action)
|
|
||||||
if not handler:
|
|
||||||
_err(f"未知 action: {action!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