officecli

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

officecli

officecli

AI-friendly CLI for .docx, .xlsx, .pptx. Single binary, no dependencies, no Office installation needed.
适用于AI场景的.docx、.xlsx、.pptx格式CLI工具。单二进制文件,无依赖,无需安装Office。

Install

安装

If
officecli
is not installed:
bash
undefined
如果未安装officecli:
bash
undefined

macOS / Linux

macOS / Linux

Windows (PowerShell)

Windows (PowerShell)


Verify with `officecli --version`. If still not found after install, open a new terminal.

---

验证安装:执行`officecli --version`。如果安装后仍无法找到,请打开新终端。

---

Strategy

操作层级策略

L1 (read) → L2 (DOM edit) → L3 (raw XML). Always prefer higher layers. Add
--json
for structured output.
Before doc work, check Specialized Skills (bottom of this file). Fundraising decks, academic papers, financial models, dashboards, and Morph animations need their own skill loaded first —
load_skill
once, then proceed.

L1(读取)→ L2(DOM编辑)→ L3(原始XML)。始终优先使用更高层级的操作。添加
--json
参数可获取结构化输出。
处理文档前,请先查看专业技能模块(本文档末尾)。筹款演示文稿、学术论文、财务模型、仪表板和Morph动画需要先加载对应的专属技能——执行一次
load_skill
后再进行操作。

Help System (IMPORTANT)

帮助系统(重要)

When unsure about property names, value formats, or command syntax, ALWAYS run help instead of guessing. One help query beats guess-fail-retry loops.
officecli help
officecli --help
, and
officecli <cmd> --help
officecli help <cmd>
— same content.
bash
officecli help                                  # All commands + global options + schema entry points
officecli help docx                             # List all docx elements
officecli help docx paragraph                   # Full schema: properties, aliases, examples, readbacks
officecli help docx set paragraph               # Verb-filtered: only props usable with `set`
officecli help docx paragraph --json            # Structured schema (machine-readable)
Format aliases:
word
docx
,
excel
xlsx
,
ppt
/
powerpoint
pptx
. Verbs:
add
,
set
,
get
,
query
,
remove
. MCP exposes the same schema via the single
command
string param:
{"command":"help docx paragraph"}
(not a structured
{"format":...,"type":...}
object — the MCP tool has exactly one param,
command
, and passes it through to the CLI verbatim).

**当不确定属性名称、值格式或命令语法时,请务必执行帮助命令,而非猜测。**一次帮助查询胜过多次猜测-失败-重试的循环。
officecli help
officecli --help
,且
officecli <cmd> --help
officecli help <cmd>
——内容完全一致。
bash
officecli help                                  # 所有命令 + 全局参数 + 架构入口
officecli help docx                             # 列出所有docx元素
officecli help docx paragraph                   # 完整架构:属性、别名、示例、回读
officecli help docx set paragraph               # 动词过滤:仅显示可用于`set`的属性
officecli help docx paragraph --json            # 结构化架构(机器可读)
格式别名:
word
docx
excel
xlsx
ppt
/
powerpoint
pptx
。动词包括:
add
set
get
query
remove
。MCP通过单个
command
字符串参数暴露相同的架构:
{"command":"help docx paragraph"}
(并非结构化的
{"format":...,"type":...}
对象——MCP工具仅有一个
command
参数,会直接将其传递给CLI)。

Performance: Resident Mode

性能:驻留模式

Every command auto-starts a resident on first access (60s idle timeout) — file-lock conflicts are automatically avoided. Explicit
open
/
close
is still recommended for longer sessions (12min idle):
bash
officecli open report.docx       # explicitly keep in memory
officecli set report.docx ...    # no file I/O overhead
officecli close report.docx      # save and release
Opt out of auto-start:
OFFICECLI_NO_AUTO_RESIDENT=1
.
Flush only at the non-officecli boundary. officecli's own reads (
get
/
query
/
view
/
dump
) always see your latest edits, so you never need to save mid-workflow. Run
save
(keeps the resident) or
close
(flush + release) only before a non-officecli program reads the file — python-docx/openpyxl, Word, a renderer, delivery/upload. (Idle sessions auto-flush within seconds;
OFFICECLI_RESIDENT_FLUSH=each
makes every mutation flush before returning.)

首次访问时,每个命令会自动启动驻留进程(空闲超时时间60秒)——文件锁冲突会自动避免。对于较长会话(空闲超时12分钟),仍建议显式执行
open
/
close
bash
officecli open report.docx       # 显式将文件保留在内存中
officecli set report.docx ...    # 无文件I/O开销
officecli close report.docx      # 保存并释放资源
退出自动启动:设置环境变量
OFFICECLI_NO_AUTO_RESIDENT=1
仅在非officecli边界执行刷新操作。officecli自身的读取操作(
get
/
query
/
view
/
dump
)始终会显示最新编辑内容,因此工作流程中无需中途保存。仅在非officecli程序读取文件前执行
save
(保留驻留进程)或
close
(刷新并释放进程)——比如python-docx/openpyxl、Word、渲染器、交付/上传工具。(空闲会话会在数秒内自动刷新;设置
OFFICECLI_RESIDENT_FLUSH=each
可让每次修改操作返回前都执行刷新。)

Quick Start

快速入门

PPT:
bash
officecli create slides.pptx
officecli add slides.pptx / --type slide --prop title="Q4 Report" --prop background=1A1A2E
officecli add slides.pptx '/slide[1]' --type shape --prop text="Revenue grew 25%" --prop x=2cm --prop y=5cm --prop font=Arial --prop size=24 --prop color=FFFFFF
Word:
bash
officecli create report.docx
officecli add report.docx /body --type paragraph --prop text="Executive Summary" --prop style=Heading1
officecli add report.docx /body --type paragraph --prop text="Revenue increased by 25% year-over-year."
Excel:
bash
officecli create data.xlsx
officecli set data.xlsx /Sheet1/A1 --prop value="Name" --prop bold=true
officecli set data.xlsx /Sheet1/A2 --prop value="Alice"

PPT:
bash
officecli create slides.pptx
officecli add slides.pptx / --type slide --prop title="Q4 Report" --prop background=1A1A2E
officecli add slides.pptx '/slide[1]' --type shape --prop text="Revenue grew 25%" --prop x=2cm --prop y=5cm --prop font=Arial --prop size=24 --prop color=FFFFFF
Word:
bash
officecli create report.docx
officecli add report.docx /body --type paragraph --prop text="Executive Summary" --prop style=Heading1
officecli add report.docx /body --type paragraph --prop text="Revenue increased by 25% year-over-year."
Excel:
bash
officecli create data.xlsx
officecli set data.xlsx /Sheet1/A1 --prop value="Name" --prop bold=true
officecli set data.xlsx /Sheet1/A2 --prop value="Alice"

L1: Create, Read & Inspect

L1:创建、读取与检查

bash
officecli create <file>               # Create blank .docx/.xlsx/.pptx (type from extension)
officecli view <file> <mode>          # outline | stats | issues | text | annotated | html
officecli get <file> <path> --depth N # Get a node and its children [--json]
officecli query <file> <selector>     # CSS-like query
officecli validate <file>             # Validate against OpenXML schema
bash
officecli create <file>               # 创建空白.docx/.xlsx/.pptx文件(类型由扩展名决定)
officecli view <file> <mode>          # 查看模式:outline | stats | issues | text | annotated | html
officecli get <file> <path> --depth N # 获取节点及其子节点 [--json]
officecli query <file> <selector>     # CSS类查询
officecli validate <file>             # 验证文件是否符合OpenXML架构

view modes

查看模式

ModeDescriptionUseful flags
outline
Document structure
stats
Statistics (pages, words, shapes)
issues
Formatting/content/structure problems
--type format|content|structure
,
--limit N
text
Plain text extraction
--start N --end N
,
--max-lines N
annotated
Text with formatting annotations
html
Static HTML snapshot — same renderer as
watch
, no server needed
--browser
,
--page N
(docx),
--start N --end N
(pptx)
screenshot
/
svg
/
pdf
/
forms
PNG via headless browser / SVG (pptx slide) / PDF via exporter plugin / form-fields JSON via format-handler plugin
-o
,
--screenshot-width/-height
, pptx
--grid N
Use
view html
for one-shot snapshots (CI artifacts, archival, diffing); use
watch
when you need live refresh or browser-side click-to-select.
模式描述实用参数
outline
文档结构
stats
统计信息(页数、字数、形状数量等)
issues
格式/内容/结构问题
--type format|content|structure
,
--limit N
text
纯文本提取
--start N --end N
,
--max-lines N
annotated
带格式标注的文本
html
静态HTML快照——与
watch
使用相同渲染器,无需服务器
--browser
,
--page N
(docx),
--start N --end N
(pptx)
screenshot
/
svg
/
pdf
/
forms
通过无头浏览器生成PNG / SVG(pptx幻灯片) / 通过导出插件生成PDF / 通过格式处理插件生成表单字段JSON
-o
,
--screenshot-width/-height
, pptx
--grid N
一次性快照(CI产物、归档、对比)使用
view html
;需要实时刷新或浏览器端点击选择时使用
watch

get

get命令

Any XML path via element localName. Use
--depth N
to expand children. Add
--json
for structured output. Default text output is grep-friendly:
path (type) "text" key=val key=val ...
bash
officecli get report.docx '/body/p[3]' --depth 2 --json
officecli get slides.pptx '/slide[1]' --depth 1          # list all shapes on slide 1
officecli get data.xlsx '/Sheet1/B2' --json
通过元素本地名称指定任意XML路径。使用
--depth N
展开子节点。添加
--json
参数获取结构化输出。默认文本输出便于grep筛选:
path (type) "text" key=val key=val ...
bash
officecli get report.docx '/body/p[3]' --depth 2 --json
officecli get slides.pptx '/slide[1]' --depth 1          # 列出第1张幻灯片上的所有形状
officecli get data.xlsx '/Sheet1/B2' --json

Stable ID Addressing

稳定ID寻址

Elements with stable IDs return
@attr=value
paths instead of positional indices. Prefer these in multi-step workflows — positional indices shift on insert/delete, stable IDs do not.
/slide[1]/shape[@id=550950021]                    # PPT shape
/slide[1]/table[@id=1388430425]/tr[1]/tc[2]       # PPT table
/body/p[@paraId=1A2B3C4D]                         # Word paragraph
/comments/comment[@commentId=1]                    # Word comment
PPT also accepts
@name=
(e.g.
shape[@name=Title 1]
), with morph
!!
prefix awareness. Elements without stable IDs (slide, run, tr/tc, row) fall back to positional indices.
带有稳定ID的元素会返回
@attr=value
格式的路径,而非位置索引。在多步骤工作流程中优先使用此类路径——位置索引会在插入/删除操作后发生变化,而稳定ID不会。
/slide[1]/shape[@id=550950021]                    # PPT形状
/slide[1]/table[@id=1388430425]/tr[1]/tc[2]       # PPT表格
/body/p[@paraId=1A2B3C4D]                         # Word段落
/comments/comment[@commentId=1]                    # Word注释
PPT还支持
@name=
格式(例如
shape[@name=Title 1]
),并兼容morph的
!!
前缀。无稳定ID的元素(幻灯片、run、tr/tc、行)会回退到位置索引。

query

query命令

CSS-like selectors:
[attr=value]
,
[attr!=value]
,
[attr~=text]
,
[attr>=value]
,
[attr<=value]
,
:contains("text")
,
:empty
,
:has(formula)
,
:no-alt
. Boolean
and
/
or
supported across
query
/
set
/
remove
:
cell[value>5000 or value<100]
,
cell[(type=Number or type=Date) and value>0]
. Excel row-by-column-name:
Sheet1!row[Salary>5000]
.
set
accepts selectors and Excel-native paths (parity with
get
/
query
). Bare unscoped selectors rejected on
set
/
remove
.
bash
officecli query report.docx 'paragraph[style=Normal] > run[font!=Arial]'
officecli query slides.pptx 'shape[fill=FF0000]'

CSS类选择器:
[attr=value]
,
[attr!=value]
,
[attr~=text]
,
[attr>=value]
,
[attr<=value]
,
:contains("text")
,
:empty
,
:has(formula)
,
:no-alt
query
/
set
/
remove
支持布尔
and
/
or
cell[value>5000 or value<100]
,
cell[(type=Number or type=Date) and value>0]
。Excel按列名选择行:
Sheet1!row[Salary>5000]
set
命令支持选择器和Excel原生路径(与
get
/
query
兼容)。
set
/
remove
命令不接受未限定范围的选择器。
bash
officecli query report.docx 'paragraph[style=Normal] > run[font!=Arial]'
officecli query slides.pptx 'shape[fill=FF0000]'

Watch & Interactive Selection

实时预览与交互式选择

Live HTML preview that auto-refreshes on every file change. Browsers can click / shift-click / box-drag to select shapes; the CLI can read the current browser selection and act on it.
bash
officecli watch <file> [--port N]      # Start preview server (default port 26315)
officecli unwatch <file>               # Stop
officecli goto <file> <path>           # Scroll watching browser(s) to element (docx: p / table / tr / tc)
Open the printed
http://localhost:N
URL. Click to select; shift/cmd/ctrl+click to multi-select; drag from empty space to box-select. PPT/Word use blue outline; Excel uses native-style green selection (double-click cell to edit inline; drag a chart to reposition).
实时HTML预览,文件每次变更时自动刷新。浏览器可点击/Shift+点击/框选形状;CLI可读取当前浏览器选中内容并进行操作。
bash
officecli watch <file> [--port N]      # 启动预览服务器(默认端口26315)
officecli unwatch <file>               # 停止预览
officecli goto <file> <path>           # 将正在预览的浏览器滚动到指定元素(docx:p / table / tr / tc)
打开打印出的
http://localhost:N
链接。点击选择;Shift/Cmd/Ctrl+点击多选;从空白区域拖动进行框选。PPT/Word使用蓝色轮廓;Excel使用原生风格的绿色选中效果(双击单元格可在线编辑;拖动图表可重新定位)。

get <file> selected
— read what the user clicked

get <file> selected
— 读取用户点击的内容

bash
officecli get <file> selected [--json]
Returns DocumentNodes for whatever is currently selected. Empty result if nothing selected. Exit code != 0 if no watch is running.
bash
undefined
bash
officecli get <file> selected [--json]
返回当前选中内容的DocumentNodes。若无选中内容则返回空结果。若未运行watch进程,退出码不为0。
bash
undefined

User clicks shapes in the browser, then asks "make these red"

用户在浏览器中点击形状,然后要求“将这些设为红色”

PATHS=$(officecli get deck.pptx selected --json | jq -r '.data.Results[].path') for p in $PATHS; do officecli set deck.pptx "$p" --prop fill=FF0000; done
undefined
PATHS=$(officecli get deck.pptx selected --json | jq -r '.data.Results[].path') for p in $PATHS; do officecli set deck.pptx "$p" --prop fill=FF0000; done
undefined

Key properties

关键特性

  • Selection survives file edits. Paths use stable
    @id=
    form.
  • All connected browsers share one selection. Last-write-wins.
  • Same-file single-watch. A given file can have only one watch process at a time.
  • Group shapes select as a whole. Drilling into individual children of a group is not supported in v1.
  • Coverage:
    .pptx
    shapes/pictures/tables/charts/connectors/groups;
    .docx
    top-level paragraphs and tables. Inherited layout/master decorations and Word nested elements (table cells, run-level) are not addressable.
    .xlsx
    does not emit
    data-path
    mark
    /
    selection
    on xlsx always resolve
    stale=true
    (v2 candidate).
  • 选中状态在文件编辑后保持不变。路径使用稳定的
    @id=
    格式。
  • 所有连接的浏览器共享同一个选中状态。最后一次操作生效。
  • 单个文件仅支持一个watch进程。一个文件同一时间只能有一个watch进程运行。
  • 组合形状作为整体被选中。v1版本不支持深入到组合形状的单个子元素。
  • 覆盖范围
    .pptx
    的形状/图片/表格/图表/连接线/组合;
    .docx
    的顶级段落和表格。继承的布局/母版装饰和Word嵌套元素(表格单元格、运行级)无法寻址。
    .xlsx
    不输出
    data-path
    ——xlsx上的
    mark
    /
    selection
    始终返回
    stale=true
    (v2版本候选特性)。

Marks — edit proposals waiting for review

标记(Marks)——待审核的编辑建议

Use
mark
when changes need human review BEFORE they hit the file. Marks live in the watch process only; a separate
set
pipeline applies accepted ones. For one-shot changes use
set
directly; for permanent file annotations use
add --type comment
(Word native).
bash
officecli mark <file> <path> [--prop find=... color=... note=... tofix=... regex=true] [--json]
officecli unmark <file> [--path <p> | --all] [--json]
officecli get-marks <file> [--json]
Props:
find
(literal or regex when
regex=true
; raw form
find='r"[abc]"'
),
color
(hex /
rgb(...)
/ 22 named whitelist),
note
,
tofix
(drives apply pipeline). Path must be
data-path
format from watch HTML — see subskills for full pipeline.

当修改需要人工审核后再应用到文件时,使用
mark
。标记仅存在于watch进程中;单独的
set
流水线会应用已确认的标记。一次性修改直接使用
set
;永久文件注释使用
add --type comment
(Word原生注释)。
bash
officecli mark <file> <path> [--prop find=... color=... note=... tofix=... regex=true] [--json]
officecli unmark <file> [--path <p> | --all] [--json]
officecli get-marks <file> [--json]
属性说明:
find
(文本或正则表达式,设置
regex=true
时生效;原始格式为
find='r"[abc]"'
)、
color
(十六进制 /
rgb(...)
/ 22种预定义命名颜色)、
note
tofix
(驱动应用流水线)。路径必须为watch HTML中的
data-path
格式——请查看子技能获取完整流水线说明。

L2: DOM Operations

L2:DOM操作

set — modify properties

set — 修改属性

bash
officecli set <file> <path> --prop key=value [--prop ...]
Any XML attribute is settable via element path (found via
get --depth N
) — even attributes not currently present. Without
find=
,
set
applies format to the entire element.
Value formats:
TypeFormatExamples
ColorsHex (with/without
#
), named, RGB, theme
FF0000
,
#FF0000
,
red
,
rgb(255,0,0)
,
accent1
..
accent6
SpacingUnit-qualified
12pt
,
0.5cm
,
1.5x
,
150%
DimensionsEMU or suffixed
914400
,
2.54cm
,
1in
,
72pt
,
96px
Dotted-attr aliases
font.<attr>
forms accepted on shape/run/paragraph/table/row/cell/section/styles, e.g.
--prop font.color=red --prop font.bold=true --prop font.size=14pt
. Run
officecli help <fmt> <element>
for the full list.
bash
officecli set <file> <path> --prop key=value [--prop ...]
任何XML属性都可通过元素路径设置(通过
get --depth N
查找路径)——即使属性当前不存在。若未指定
find=
set
会将格式应用到整个元素。
值格式:
类型格式示例
颜色十六进制(带/不带
#
)、命名颜色、RGB、主题色
FF0000
,
#FF0000
,
red
,
rgb(255,0,0)
,
accent1
..
accent6
间距带单位的数值
12pt
,
0.5cm
,
1.5x
,
150%
尺寸EMU或带后缀的数值
914400
,
2.54cm
,
1in
,
72pt
,
96px
点属性别名——在形状/运行/段落/表格/行/单元格/节/样式上支持
font.<attr>
格式,例如
--prop font.color=red --prop font.bold=true --prop font.size=14pt
。执行
officecli help <fmt> <element>
查看完整列表。

find — format or replace matched text

find — 格式化或替换匹配文本

Use top-level
--find
/
--replace
on
set
(and
--find
on
query
). Legacy
--prop find=X
still works but emits a hint.
bash
undefined
set
命令中使用顶级参数
--find
/
--replace
query
命令仅支持
--find
)。旧格式
--prop find=X
仍可使用,但会提示建议。
bash
undefined

Format matched text (auto-splits runs)

格式化匹配文本(自动拆分run)

officecli set doc.docx '/body/p[1]' --find weather --prop bold=true --prop color=red
officecli set doc.docx '/body/p[1]' --find weather --prop bold=true --prop color=red

Regex matching (regex= still a prop flag)

正则匹配(regex=仍为属性标志)

officecli set doc.docx '/body/p[1]' --find '\d+%' --prop regex=true --prop color=red
officecli set doc.docx '/body/p[1]' --find '\d+%' --prop regex=true --prop color=red

Replace text (use
/
for whole-document scope)

替换文本(使用
/
表示全文档范围)

officecli set doc.docx / --find draft --replace final
officecli set doc.docx / --find draft --replace final

docx: tracked Find&Replace

docx:带追踪的查找替换

officecli set doc.docx / --find draft --replace final --prop revision.author=Alice
officecli set doc.docx / --find draft --replace final --prop revision.author=Alice

PPT — same syntax, different paths

PPT — 语法相同,路径不同

officecli set slides.pptx / --find draft --replace final

**Path controls search scope:** `/` = whole document, `/body/p[1]` or `/slide[N]/shape[M]` = specific element, `/header[1]` / `/footer[1]` = headers/footers.

**Notes:**
- Case-sensitive by default. Case-insensitive: `--prop 'find=(?i)error' --prop regex=true`
- Matches work across run boundaries
- No match = silent success. `--json` includes `"matched": N`
- **Excel:** only `find` + `replace` supported (no find + format props)
officecli set slides.pptx / --find draft --replace final

**路径控制搜索范围**:`/` = 全文档,`/body/p[1]` 或 `/slide[N]/shape[M]` = 指定元素,`/header[1]` / `/footer[1]` = 页眉/页脚。

**注意事项:**
- 默认区分大小写。不区分大小写:`--prop 'find=(?i)error' --prop regex=true`
- 匹配可跨run边界
- 无匹配时静默成功。`--json`返回结果包含`"matched": N`
- **Excel:**仅支持`find` + `replace`(不支持find + 格式属性)

add — add elements or clone

add — 添加元素或克隆

bash
officecli add <file> <parent> --type <type> [--prop ...]
officecli add <file> <parent> --type <type> --after <path> [--prop ...]   # insert after anchor
officecli add <file> <parent> --type <type> --before <path> [--prop ...]  # insert before anchor
officecli add <file> <parent> --type <type> --index N [--prop ...]        # 0-based position (legacy)
officecli add <file> <parent> --from <path>                               # clone existing element
--after
,
--before
,
--index
are mutually exclusive. No position flag = append to end.
Element types (with aliases):
FormatTypes
pptxslide (incl. hidden), shape (font.latin/ea/cs, direction=rtl, underline.color, highlight=COLOR (Add/Set/Get/HTML preview), effective.X+effective.X.src; arrow alias for rightArrow; slideMaster/slideLayout typed add/set/remove), picture (SVG, brightness/contrast/glow/shadow, rotation, link, tooltip), chart (direction=rtl, pieOfPie, barOfPie, axisLine/gridline per-attr setters, animation+chartBuild=byCategory
docxparagraph (direction/font.latin/ea/cs, bold.cs/italic.cs/size.cs, lang.latin/ea/cs, wordWrap, framePr.*, tabs shorthand), run (lang slots, direction, underline.color, position half-pts, revision.type=ins|del|format|moveFrom|moveTo + revision.action=accept|reject with .author/.date — bare
@author=
/
@type=
selector on
set /revision[...]
for filtered accept/reject, but
query 'revision[...]'
needs the dotted
revision.author=
/
revision.type=
form; move+revision is run-level paths only, not paragraph-level; range=START:END on a paragraph/shape path formats a char span by explicit 0-based half-open offset instead of addressing a run — the offset sibling of find=), table (direction=rtl, hMerge, cantSplit on row/nowrap on cell (both add+set), virtual column ops: add/remove/move/copyfrom on /body/tbl[N]/col), row (tr), cell (td), image, header/footer (direction), section (pageNumFmt full enum, direction=rtl, rtlGutter, pgBorders=box), bookmark, comment, footnote, endnote, formfield, sdt, chart, equation, field (28 types), hyperlink, style (direction, indents, pbdr, lineSpacing on Add/Set), toc, watermark, break, ole, num/abstractNum/lvl, tab, textbox/shape (add-mostly — Get returns raw XML preview only, no structured readback; Set is limited to width/height/geometry/fill/line.*; position is
anchor.x
/
anchor.y
not bare x/y; textbox-only
textDirection
/rotation/gradient/shadow — docx shape itself has neither rotation nor gradient), embedded OLE round-trip on dump→batch, diagram (add-only mermaid → native shapes or rendered image,
--type diagram
/
flowchart
, no x/y at add-time — reposition via
set /body/group[N]
). docDefaults.rtl, autoHyphenation,
get /
exposes locale + /comments /footnotes /endnotes.
create --minimal
for raw OOXML scaffolding.
xlsxsheet (visible/hidden/veryHidden, print margins, printTitleRows/Cols, rightToLeft sheetView, cascade-aware rename), row (c{N}= cell-content shorthand; add accepts --from /Sheet/col[L]; formula-ref rewrite on insert), col (formula-ref rewrite, named-range follow on move), cell (type=richtext+runs, merge=range/sweep, direction=rtl, phonetic; --shift left|up on remove, shift=right|down on add — Excel UI dialog parity; formula auto-detect; OFFSET/INDIRECT in calc), chart (per-axis RTL/title, anchor=x,y,w,h, pareto), image (SVG), comment (direction=rtl), table (listobject), namedrange (definedname, volatile,
[@name=X]
; formula-body inlined at parse), pivottable (cache CoW + cross-pivot sharing, labelFilter=field:type:value add-time-only, topN=integer add-time-only, fillDownLabels is an alias of repeatLabels not a separate feature, calculatedField), sparkline, validation, autofilter, shape, textbox, CF (databar/colorscale/iconset/formulacf/cellIs/topN/aboveAverage), ole, csv. Query supports
merge
/
mergedrange
. Workbook: password. Shape selector enumerates leaves inside grpSp.
bash
officecli add <file> <parent> --type <type> [--prop ...]
officecli add <file> <parent> --type <type> --after <path> [--prop ...]   # 在锚点后插入
officecli add <file> <parent> --type <type> --before <path> [--prop ...]  # 在锚点前插入
officecli add <file> <parent> --type <type> --index N [--prop ...]        # 0-based位置(旧格式)
officecli add <file> <parent> --type <type> --from <path>                               # 克隆现有元素
--after
--before
--index
互斥。未指定位置参数时,默认追加到末尾。
元素类型(含别名):
格式类型
pptxslide(含隐藏幻灯片)、shape(font.latin/ea/cs、direction=rtl、underline.color、highlight=COLOR(支持Add/Set/Get/HTML预览)、effective.X+effective.X.src;arrow为rightArrow的别名;支持slideMaster/slideLayout类型的add/set/remove)、picture(SVG、亮度/对比度/发光/阴影、旋转、链接、工具提示)、chart(direction=rtl、复合饼图、复合条形图、轴/网格线的独立属性设置器、animation+chartBuild=byCategory
docxparagraph(direction/font.latin/ea/cs、bold.cs/italic.cs/size.cs、lang.latin/ea/cs、wordWrap、framePr.、tabs简写)、run(lang插槽、direction、underline.color、位置半磅值、revision.type=ins|del|format|moveFrom|moveTo + revision.action=accept|reject,支持.author/.date——
set /revision[...]
可使用裸
@author=
/
@type=
选择器进行过滤式接受/拒绝,但
query 'revision[...]'
需要使用点格式
revision.author=
/
revision.type=
;移动+修订仅支持run级路径,不支持段落级;range=START:END在段落/形状路径上通过显式0-based半开偏移量格式化字符范围,而非寻址run——是find=的偏移量替代方案)、table(direction=rtl、hMerge、行的cantSplit/单元格的nowrap(均支持add+set)、虚拟列操作:支持/body/tbl[N]/col的add/remove/move/copyfrom)、row(tr)、cell(td)、image、header/footer(direction)、section(pageNumFmt完整枚举、direction=rtl、rtlGutter、pgBorders=box)、bookmark、comment、footnote、endnote、formfield、sdt、chart、equation、field(28种类型)、hyperlink、style(direction、缩进、pbdr、行间距,支持Add/Set)、toc、watermark、break、ole、num/abstractNum/lvltabtextbox/shape(主要支持添加——Get仅返回原始XML预览,无结构化回读;Set仅支持width/height/geometry/fill/line.
;位置使用
anchor.x
/
anchor.y
而非裸x/y;仅textbox支持
textDirection
/旋转/渐变/阴影——docx形状本身不支持旋转或渐变)、嵌入式OLE往返导出(dump→batch)diagram(仅支持添加:mermaid→原生形状或渲染图片,
--type diagram
/
flowchart
,添加时不支持x/y——通过
set /body/group[N]
重新定位)。docDefaults.rtl、autoHyphenation、
get /
暴露区域设置 + /comments /footnotes /endnotes。
create --minimal
用于生成原始OOXML框架。
xlsxsheet(可见/隐藏/非常隐藏、打印边距、printTitleRows/Cols、rightToLeft sheetView、支持级联重命名)、row(c{N}=单元格内容简写;add接受--from /Sheet/col[L];插入时自动重写公式引用)、col(自动重写公式引用、移动时跟随命名范围)、cell(type=richtext+runs、merge=range/sweep、direction=rtl、拼音;remove时--shift left|up,add时shift=right|down——与Excel UI对话框一致;自动检测公式;支持OFFSET/INDIRECT计算)、chart(每轴RTL/标题、anchor=x,y,w,h、帕累托图)、image(SVG)、comment(direction=rtl)、table(listobject)、namedrange(definedname、volatile、
[@name=X]
;解析时内联公式主体)、pivottable(缓存写时复制 + 跨透视表共享、labelFilter=field:type:value仅添加时有效、topN=integer仅添加时有效、fillDownLabels是repeatLabels的别名而非独立特性、calculatedField)、sparkline、validation、autofilter、shape、textbox、CF(数据条/色阶/图标集/公式条件/单元格值/前N项/高于平均值)、ole、csv。Query支持
merge
/
mergedrange
。工作簿:password。Shape选择器枚举grpSp内的叶子元素。

Pivot tables (xlsx)

Excel数据透视表

bash
officecli add data.xlsx /Sheet1 --type pivottable \
  --prop source="Sheet1!A1:E100" --prop rows=Region,Category \
  --prop cols=Year --prop values="Sales:sum,Qty:count" \
  --prop grandTotals=rows --prop subtotals=off --prop sort=asc
Key props:
rows
,
cols
,
values
(Field:func[:showDataAs]),
filters
,
source
,
position
,
layout
(compact/outline/tabular),
repeatLabels
,
blankRows
,
aggregate
,
showDataAs
(percent_of_total/row/col, running_total),
grandTotals
,
subtotals
,
sort
. Aggregators: sum, count, average, max, min, product, stdDev, stdDevp, var, varp, countNums. Date columns auto-group. Run
officecli help xlsx pivottable
for full schema.
bash
officecli add data.xlsx /Sheet1 --type pivottable \
  --prop source="Sheet1!A1:E100" --prop rows=Region,Category \
  --prop cols=Year --prop values="Sales:sum,Qty:count" \
  --prop grandTotals=rows --prop subtotals=off --prop sort=asc
关键属性:
rows
cols
values
(字段:函数[:showDataAs])、
filters
source
position
layout
(紧凑/大纲/表格)、
repeatLabels
blankRows
aggregate
showDataAs
(占总计百分比/行/列、累计总和)、
grandTotals
subtotals
sort
。聚合函数:sum、count、average、max、min、product、stdDev、stdDevp、var、varp、countNums。日期列自动分组。执行
officecli help xlsx pivottable
查看完整架构。

Document-level properties (all formats)

文档级属性(所有格式)

bash
officecli set doc.docx / --prop docDefaults.font=Arial --prop docDefaults.fontSize=11pt
officecli set doc.docx / --prop protection=forms --prop evenAndOddHeaders=true
officecli set data.xlsx / --prop calc.mode=manual --prop calc.refMode=r1c1
officecli set slides.pptx / --prop defaultFont=Arial --prop show.loop=true --prop print.what=handouts
Run
officecli help <format> /
for all document-level properties (docDefaults, docGrid, CJK spacing, calc, print, show, theme, extended).
bash
officecli set doc.docx / --prop docDefaults.font=Arial --prop docDefaults.fontSize=11pt
officecli set doc.docx / --prop protection=forms --prop evenAndOddHeaders=true
officecli set data.xlsx / --prop calc.mode=manual --prop calc.refMode=r1c1
officecli set slides.pptx / --prop defaultFont=Arial --prop show.loop=true --prop print.what=handouts
执行
officecli help <format> /
查看所有文档级属性(docDefaults、docGrid、CJK间距、calc、print、show、theme、extended)。

Sort (xlsx)

Excel排序

bash
officecli set data.xlsx /Sheet1 --prop sort="C desc" --prop sortHeader=true
officecli set data.xlsx '/Sheet1/A1:D100' --prop sort="A asc" --prop sortHeader=true
Format:
COL DIR[, COL DIR ...]
. Rejects ranges with merged cells or formulas. Sidecar metadata (hyperlinks, comments, conditional formatting, drawings) follows rows automatically.
bash
officecli set data.xlsx /Sheet1 --prop sort="C desc" --prop sortHeader=true
officecli set data.xlsx '/Sheet1/A1:D100' --prop sort="A asc" --prop sortHeader=true
格式:
COL DIR[, COL DIR ...]
。拒绝包含合并单元格或公式的范围。附带元数据(超链接、注释、条件格式、绘图)会自动跟随行移动。

Text-anchored insert (
--after find:X
/
--before find:X
)

文本锚定插入(
--after find:X
/
--before find:X

Locate an insertion point by text match within a paragraph. Inline types (run, picture, hyperlink) insert within the paragraph; block types (table, paragraph) auto-split it. PPT only supports inline.
bash
undefined
通过段落内的文本匹配定位插入点。内联类型(run、picture、hyperlink)插入到段落内;块类型(table、paragraph)会自动拆分段落。仅PPT支持内联插入。
bash
undefined

Word: inline run after matched text

Word:在匹配文本后插入内联run

officecli add doc.docx '/body/p[1]' --type run --after find:weather --prop text=" (sunny)"
officecli add doc.docx '/body/p[1]' --type run --after find:weather --prop text=" (sunny)"

Word: block table after matched text (auto-splits paragraph)

Word:在匹配文本后插入块级表格(自动拆分段落)

officecli add doc.docx '/body/p[1]' --type table --after "find:First sentence." --prop rows=2 --prop cols=2
undefined
officecli add doc.docx '/body/p[1]' --type table --after "find:First sentence." --prop rows=2 --prop cols=2
undefined

Clone

克隆

officecli add <file> / --from '/slide[1]'
— copies with all cross-part relationships.
officecli add <file> / --from '/slide[1]'
— 复制元素及其所有跨部件关联关系。

move, swap, remove

move、swap、remove

bash
officecli move <file> <path> [--to <parent>] [--index N] [--after <path>] [--before <path>]
officecli swap <file> <path1> <path2>
officecli remove <file> '/body/p[4]'
When using
--after
or
--before
,
--to
can be omitted — the target container is inferred from the anchor.
bash
officecli move <file> <path> [--to <parent>] [--index N] [--after <path>] [--before <path>]
officecli swap <file> <path1> <path2>
officecli remove <file> '/body/p[4]'
使用
--after
--before
时,可省略
--to
——目标容器会从锚点推断得出。

batch — multiple operations in one save cycle

batch — 单次保存周期内执行多个操作

Atomic by default (v1.0.137+): every item still runs and is reported (so
N succeeded, M failed
stays meaningful and every failure surfaces), but if any item fails the whole batch rolls back — the file on disk is left byte-identical to before the batch ran (confirmed live in both standalone and resident mode). Use
--best-effort
to restore the old apply-what-succeeds behavior (useful for lossy
dump→batch
replays where losing the whole thing over one unsupported item is worse than a partial result).
--stop-on-error
only changes how early the run stops (remaining items are
skipped
), not whether what ran gets kept — combine it with
--best-effort
if you want "stop at first failure but keep what already succeeded."
--force
is unrelated — it's only the docx-protection bypass. Failed items carry a machine-readable
code
field (same list as
error.code
); a rolled-back batch's JSON summary carries
"atomicRolledBack": true
.
officecli dump <file> [<path>]
emits a replayable batch JSON for round-trip —
.docx
(full coverage),
.pptx
(text/tables/pictures/charts/notes/theme + OLE/3D/video/audio/SmartArt/morph/p15 transitions via raw-set passthrough), and
.xlsx
(cells/formulas/styles + tables, conditional formatting, validations, comments, charts, sparklines, pictures, shapes, pivot tables; slicers/chartEx/OLE via verbatim carrier). Path defaults to
/
(whole document); pass a subtree path (docx:
/body
,
/body/p[N]
,
/body/tbl[N]
,
/theme
,
/settings
,
/numbering
,
/styles
; xlsx:
/SheetName
,
/sheet[N]
) to scope the dump.
officecli refresh <file.docx>
recalculates TOC page numbers / PAGE / cross-references after replay (Word backend on Windows; headless-HTML fallback elsewhere).
officecli plugins list
extends support to
.doc
,
.hwpx
,
.pdf
export.
bash
echo '[
  {"command":"set","path":"/Sheet1/A1","props":{"value":"Name","bold":"true"}},
  {"command":"set","path":"/Sheet1/B1","props":{"value":"Score","bold":"true"}}
]' | officecli batch data.xlsx --json

officecli batch data.xlsx --commands '[{"op":"set","path":"/Sheet1/A1","props":{"value":"Done"}}]' --json
officecli batch data.xlsx --input updates.json --best-effort --json   # keep whatever succeeds even if some items fail
Supports:
add
,
set
,
get
,
query
,
remove
,
move
,
swap
,
view
,
raw
,
raw-set
,
validate
. Fields:
command
(or
op
),
path
,
parent
,
type
,
from
,
to
,
index
,
after
,
before
,
props
,
selector
,
mode
,
depth
,
part
,
xpath
,
action
,
xml
.

默认原子性(v1.0.137+):每个操作仍会执行并报告(因此
N成功,M失败
仍有意义,且每个失败都会暴露),但如果任何操作失败,整个批次会回滚——磁盘上的文件会恢复到批次执行前的字节级状态(在独立模式和驻留模式下均已验证)。使用
--best-effort
恢复旧的“成功即应用”行为(适用于有损
dump→batch
重放场景,此时因一个不支持的项丢失整个文件比部分结果更糟)。
--stop-on-error
仅改变运行停止的时机(剩余项标记为
skipped
),不影响已执行操作的保留——若要实现“首次失败即停止但保留已成功操作”,请将其与
--best-effort
结合使用。
--force
无关——仅用于绕过docx保护。失败项包含机器可读的
code
字段(与
error.code
列表相同);回滚批次的JSON摘要包含
"atomicRolledBack": true
officecli dump <file> [<path>]
输出可重放的batch JSON用于往返导出——
.docx
(完整覆盖)、
.pptx
(文本/表格/图片/图表/备注/主题 + 通过raw-set传递OLE/3D/视频/音频/SmartArt/morph/p15过渡)、
.xlsx
(单元格/公式/样式 + 表格、条件格式、验证、注释、图表、迷你图、图片、形状、数据透视表;切片器/chartEx/OLE通过逐字载体)。路径默认为
/
(全文档);传递子树路径(docx:
/body
/body/p[N]
/body/tbl[N]
/theme
/settings
/numbering
/styles
;xlsx:
/SheetName
/sheet[N]
)可限定范围。
officecli refresh <file.docx>
在重放后重新计算TOC页码/PAGE/交叉引用(Windows使用Word后端;其他平台使用无头HTML回退)。
officecli plugins list
扩展支持
.doc
.hwpx
.pdf
导出。
bash
echo '[
  {"command":"set","path":"/Sheet1/A1","props":{"value":"Name","bold":"true"}},
  {"command":"set","path":"/Sheet1/B1","props":{"value":"Score","bold":"true"}}
]' | officecli batch data.xlsx --json

officecli batch data.xlsx --commands '[{"op":"set","path":"/Sheet1/A1","props":{"value":"Done"}}]' --json
officecli batch data.xlsx --input updates.json --best-effort --json   # 即使部分项失败,仍保留成功的操作
支持的操作:
add
set
get
query
remove
move
swap
view
raw
raw-set
validate
。字段:
command
(或
op
)、
path
parent
type
from
to
index
after
before
props
selector
mode
depth
part
xpath
action
xml

L3: Raw XML

L3:原始XML

Use when L2 cannot express what you need. No xmlns declarations needed — prefixes auto-registered.
bash
officecli raw <file> <part>                          # view raw XML
officecli raw-set <file> <part> --xpath "..." --action replace --xml '<w:p>...</w:p>'
officecli add-part <file> <parent>                   # create new document part (returns rId)
raw-set
actions:
append
,
prepend
,
insertbefore
,
insertafter
,
replace
,
remove
,
setattr
. Run
officecli help <format> raw
for available parts.

当L2无法满足需求时使用此层级。无需xmlns声明——前缀会自动注册。
bash
officecli raw <file> <part>                          # 查看原始XML
officecli raw-set <file> <part> --xpath "..." --action replace --xml '<w:p>...</w:p>'
officecli add-part <file> <parent>                   # 创建新文档部件(返回rId)
raw-set
操作类型:
append
prepend
insertbefore
insertafter
replace
remove
setattr
。执行
officecli help <format> raw
查看可用部件。

Common Pitfalls

常见陷阱

PitfallCorrect Approach
--name "foo"
Use
--prop name="foo"
— all attributes go through
--prop
Unquoted
[N]
paths in zsh/bash
Always quote:
'/slide[1]'
or
"/slide[1]"
(shell glob-expands brackets)
PPT
shape[1]
for content
shape[1]
is typically the title placeholder. Use
shape[2]+
for content shapes
/shape[myname]
Name indexing not supported. Use numeric index or
@name=
(PPT only)
Guessing property namesRun
officecli help <format> <element>
to see exact names
Modifying an open fileClose the file in PowerPoint/WPS first
\n
in shell strings
Use
\\n
for newlines in
--prop text="..."
$
in shell text
--prop text="$15M"
strips
$15
. Use single quotes:
--prop text='$15M'
, or heredoc batch

陷阱正确做法
--name "foo"
使用
--prop name="foo"
——所有属性都通过
--prop
传递
zsh/bash中路径未加引号的
[N]
始终加引号:
'/slide[1]'
"/slide[1]"
(shell会展开括号通配符)
PPT中使用
shape[1]
获取内容
shape[1]
通常是标题占位符。使用
shape[2]+
获取内容形状
/shape[myname]
不支持名称索引。使用数字索引或
@name=
(仅PPT支持)
猜测属性名称执行
officecli help <format> <element>
查看准确名称
修改已打开的文件先在PowerPoint/WPS中关闭文件
shell字符串中的
\n
--prop text="..."
中使用
\\n
表示换行
shell文本中的
$
--prop text="$15M"
会丢失
$15
。使用单引号:
--prop text='$15M'
,或使用heredoc批量处理

Specialized Skills

专业技能

officecli load_skill <name>
— output is a SKILL.md, follow its rules.
Loading rule:
  • Pick the most specific match in "When to use"; if none fits, load the format default (
    word
    /
    pptx
    /
    excel
    ).
  • Scenes already contain the format default's rules — load one skill per artifact, never stack.
  • Loaded rules persist across turns; don't re-load each reply.
  • Two distinct artifacts → two separate loads.
officecli load_skill <name>
——输出为SKILL.md,请遵循其中的规则。
加载规则:
  • 在“适用场景”中选择最匹配的技能;若无匹配项,加载格式默认技能(
    word
    /
    pptx
    /
    excel
    )。
  • 场景已包含格式默认技能的规则——每个工件加载一个技能,切勿叠加。
  • 加载的规则会在多轮对话中保留;无需每次回复都重新加载。
  • 两个不同的工件→分别加载两个技能。

Word (.docx)

Word (.docx)

NameWhen to use
word
Reports, letters, memos, proposals, generic documents
academic-paper
Journal / conference / thesis: APA / Chicago / IEEE / MLA citations, equations, SEQ + PAGEREF cross-refs, multi-column journal layout, bibliography. NOT for business reports or letters (route those to
word
)
名称适用场景
word
报告、信函、备忘录、提案、通用文档
academic-paper
期刊/会议/学位论文:APA/Chicago/IEEE/MLA引用、公式、SEQ + PAGEREF交叉引用、多栏期刊布局、参考文献。不适用于商务报告或信函(请使用
word

PowerPoint (.pptx)

PowerPoint (.pptx)

NameWhen to use
pptx
Generic decks: board reviews, sales decks, all-hands, product launches
pitch-deck
Fundraising only — seed / Series A-C / SAFE / convertible / strategic raise. NOT for sales / product / board decks (route those to
pptx
)
morph-ppt
Cinematic Morph-animated presentations. NOT for static decks (route those to
pptx
)
morph-ppt-3d
3D Morph: GLB models, camera moves, depth. NOT for 2D-only Morph (route those to
morph-ppt
)
名称适用场景
pptx
通用演示文稿:董事会评审、销售演示、全员会议、产品发布
pitch-deck
仅用于筹款——种子轮/A-C轮/SAFE/可转换债券/战略融资。不适用于销售/产品/董事会演示文稿(请使用
pptx
morph-ppt
电影级Morph动画演示文稿。不适用于静态演示文稿(请使用
pptx
morph-ppt-3d
3D Morph:GLB模型、摄像机移动、景深效果。不适用于仅2D的Morph演示文稿(请使用
morph-ppt

Excel (.xlsx)

Excel (.xlsx)

NameWhen to use
excel
Generic workbooks, formulas, pivots, trackers
financial-model
Financial models, scenarios, projections. NOT for general data analysis (route those to
excel
)
data-dashboard
CSV/tabular data → KPI / analytics / executive dashboards with charts and sparklines. NOT for raw data tracking (route those to
excel
)
Example: a fundraising deck task →
officecli load_skill pitch-deck
→ use the printed rules.

名称适用场景
excel
通用工作簿、公式、数据透视表、追踪表
financial-model
财务模型、场景模拟、预测。不适用于通用数据分析(请使用
excel
data-dashboard
CSV/表格数据→KPI/分析/高管仪表板(含图表和迷你图)。不适用于原始数据追踪(请使用
excel
示例:筹款演示文稿任务→执行
officecli load_skill pitch-deck
→遵循输出的规则。

Notes

注意事项

  • Paths are 1-based (XPath convention):
    '/body/p[3]'
    = third paragraph
  • --index
    is 0-based (array convention):
    --index 0
    = first position
  • Excel exception: for
    add --type row
    and
    add --type col
    ,
    --index N
    is 1-based (matches OOXML RowIndex / column letter index).
    --index 5
    inserts at row 5 / column 5.
  • After modifications, verify with
    validate
    and/or
    view issues
  • When unsure, run
    officecli help <format> <element>
    instead of guessing
  • 路径为1-based(XPath约定):
    '/body/p[3]'
    = 第三个段落
  • --index
    0-based(数组约定):
    --index 0
    = 第一个位置
  • Excel例外:对于
    add --type row
    add --type col
    --index N
    1-based(与OOXML的RowIndex/列字母索引一致)。
    --index 5
    表示插入到第5行/第5列。
  • 修改后,请使用
    validate
    和/或
    view issues
    验证
  • 不确定时,执行
    officecli help <format> <element>
    而非猜测