OfficeCLI Examples 全指南:用 CLI 与 Python SDK 自动化 Word、Excel、PowerPoint
OfficeCLI Examples 全指南:用 CLI 与 Python SDK 自动化 Word、Excel、PowerPoint
本指南基于 OfficeCLI 仓库中的 examples/README.md 展开,系统梳理仓库内全部示例的组织方式、四件套文件约定、快速上手命令与核心编程模式。读完本文,你将掌握如何用 officecli CLI 或 Python SDK 双路径生成 .docx / .xlsx / .pptx 文档,理解 create / add / set / get / query / batch / validate 等核心动词的用法,并能直接运行仓库中的 60+ 个示例脚本作为实战模板。
Examples 全景:覆盖三大文档类型的演示矩阵
examples/ 目录是 OfficeCLI 的能力演示中心,按文档格式划分为 word/、excel/、ppt/ 三个子目录,每个示例都同时展示「操作说明 + 可运行脚本 + 预生成产物」,既是上手教程,也是回归测试集。
examples/
├── README.md # 本文件
├── word/ # Word 示例 —— *.{md,sh,py,docx}
│ ├── formulas.{md,sh,py,docx} # LaTeX 数学/化学/物理公式
│ ├── tables.{md,sh,py,docx} # 样式化表格
│ ├── textbox.{md,sh,py,docx} # 格式化文本框
│ ├── charts.{md,sh,py,docx} # 内嵌图表(含 treemap/waterfall 等 14 种类型)
│ ├── run-formatting.{md,sh,py,docx} # run/字符级属性面
│ ├── paragraph-formatting.{md,sh,py,docx} # 段落属性面
│ ├── document-formatting.{md,sh,py,docx} # 文档级属性面
│ ├── sections.{md,sh,py,docx} # 分节布局 —— 多栏、脚注/尾注属性、按节的页面设置
│ ├── content-controls.{md,sh,py,docx} # SDT 内容控件 —— 文本/下拉/组合框/日期/图片/分组录入表单
│ ├── fields.{md,sh,py,docx} # 域代码(PAGE/DATE/REF/IF/HYPERLINK)+ 自动目录
│ ├── pictures.{md,sh,py,docx} # 内嵌/浮动图片 —— 裁剪、alt、环绕、置于文字下方、绝对定位
│ ├── numbering.{md,sh,py,docx} # 列表/编号样式
│ ├── diagram.{md,sh,py,docx} # Mermaid 图表 —— 原生可编辑形状 + 高保真 PNG
│ └── revisions.{md,sh,py,docx} # 修订(tracked-change)API
├── excel/ # Excel 示例 —— *.{md,sh,py,xlsx}
│ ├── cell-formatting.{md,sh,py,xlsx} # 完整 cell 属性面(字体/填充/边框/numFmt/数据)
│ ├── conditional-formatting.{md,sh,py,xlsx}
│ ├── data-validation.{md,sh,py,xlsx} # 下拉列表、数字/日期/文本/自定义规则、输入与错误提示
│ ├── sheet-settings.{md,sh,py,xlsx} # 冻结窗格、打印区域/标题、页眉页脚、显示与保护
│ ├── sparklines.{md,sh,py,xlsx} # 单元格内迷你折线/柱形/胜负图 + 标记点
│ ├── workbook-settings.{md,sh,py,xlsx}
│ ├── pivot-tables.{md,sh,py,xlsx}
│ ├── slicers.{md,sh,py,xlsx} # 数据透视表切片器(field/caption/columnCount/rowHeight)
│ ├── shapes.{md,sh,py,xlsx} # 绘图形状 —— 几何、翻转、发光、渐变、映像、轮廓
│ ├── charts.{md,sh,py,xlsx} # 图表总览
│ └── charts/ # 按类型拆分的图表脚本 —— charts-<type>.{md,sh,py,xlsx}
│ (demo, basic, advanced, extended, area, bar, boxwhisker,
│ bubble, column, combo, histogram, line, pie, radar,
│ scatter, stock, waterfall)
└── ppt/ # PowerPoint 示例 —— *.{md,sh,py,pptx}
├── presentation.{md,sh,py,pptx}
├── presentation-settings.{md,sh,py,pptx}
├── diagram.{md,sh,py,pptx} # Mermaid 图表 —— 原生可编辑形状 + 高保真 PNG
├── animations.{md,sh,py,pptx}
├── video.{md,sh,py,pptx}
├── 3d-model.{md,sh,py,pptx}
├── charts/ # charts-<type>.{md,sh,py,pptx}
│ (column, bar, line, pie, doughnut, area, scatter,
│ bubble, radar, stock, combo, waterfall, 3d, advanced)
├── tables/ # tables-<topic>.{md,sh,py,pptx}
│ (basic, styled, merged, borders, rows-cols, financial, nested)
├── transitions/ # transitions-<topic>.{md,sh,py,pptx}
│ (basic, directional, shapes, bands, dynamic, modern, random, timing, morph)
├── shapes/ # shapes-<topic>.{md,sh,py,pptx}
│ (basic, connectors, effects, typography)
├── textboxes/ # textboxes-<topic>.{md,sh,py,pptx}
│ (basic, advanced)
├── pictures/ # pictures-basic.{md,sh,py,pptx}
├── ole/ # ole-embed.{md,sh,py,pptx} —— 内嵌 Excel/Word OLE 对象
└── templates/styles/*/build*.sh # 整场 PPT 模板生成器(仅 .sh)
四件套约定:每个示例都是 .md + .sh + .py + 产物
每个示例都标配四个文件,角色分工明确:
| 文件 | 角色 |
|---|---|
<name>.md |
讲解文档 —— 说明示例演示了什么、使用了哪些关键技术 |
<name>.sh |
CLI 构建脚本 —— 直接驱动 officecli 二进制(officecli create / add / set / close / validate) |
<name>.py |
SDK 构建脚本 —— 驱动 officecli Python SDK(import officecli;with officecli.create(...) as doc: doc.batch([...])) |
<name>.<ext> |
预生成产物(.docx / .xlsx / .pptx) |
.sh 与 .py 是等价孪生脚本——两者通过不同入口重新生成同一份输出文档。例如 examples/word/formulas.sh 逐个调用 CLI 命令,而 examples/word/formulas.py 在单个常驻会话中把全部指令打包成一次 doc.batch([...]) 往返。你完全可以根据自己的工作流任选其一。
唯一的例外是 ppt/templates/styles/*/build*.sh:它们是独立的整场 PPT 生成器而非四件套 API 示例,因此只以 .sh 形式提供,从源码结构看 examples/ppt/templates/styles/ 下每个风格目录(如 brand--aura-coffee、dark--cosmic-neon、light--watercolor-wash 等 40+ 套视觉主题)都配有对应的 build*.sh 构建脚本与产物。
各类示例覆盖的能力面
Word(docx):run/字符级格式化(字重、下划线变体、删除线、大小写、上下标、逐脚本字体、文字效果、字符间距、语言)、段落格式化(对齐/缩进/间距/分页标志/段落级 run 格式/底纹/段落标记格式/大纲级别)、LaTeX 数学公式、复杂表格、文本框与样式、编号/列表、Mermaid 图表(render=native 生成可编辑的流程图/时序图形状,render=image 生成每种 mermaid 类型的内嵌高保真 PNG)。
Excel(xlsx):跨 5 张工作表的完整 cell 属性面——字体(name/size/bold/italic/color/underline/strike)、填充(hex/named/rgb)+ 对齐(h/v/wrap/RTL)、边框(简写/全部/逐边/颜色)、数字格式(千分位/%/货币/日期/科学计数/会计专用)与数据(value/type/formula/link/locked/merge);主示例与按类型拆分的图表脚本(line、bar、pie、scatter、stock、waterfall 等)、数据透视表、数字格式与样式。
PowerPoint(pptx):幻灯片/形状构建、Morph 过渡与动画、视频与 3D 模型嵌入、Mermaid 图表(原生可编辑形状 + 连接线,或经 mermaid.js 渲染的高保真 PNG;mermaid/text/dsl/src 四种源码来源、放置框、整图 get/set/remove)、原生图表(column、bar、line、pie、doughnut、area、scatter、bubble、radar、stock、combo、waterfall、3D、advanced)、表格(基础、内置样式、合并单元格、边框、行列操作、真实金融场景整场 deck)、幻灯片切换(9 组示例覆盖全部 59 个 schema token:basic、directional、shape、band、dynamic 3D、modern 的 Page Curl/Airplane/Origami、random、timing、Morph)、形状(4 组示例覆盖完整属性面)、文本框(对齐、项目符号/编号列表、逐 run 富文本、逐脚本字体、垂直对齐与内边距)、图片(路径/URL/data-URI/name= 的 src=,各类裁剪、旋转、可点击链接)。
快速上手:同一示例,CLI 与 Python SDK 两条等价路径
每个示例都有两种等价运行方式,任选其一:
bash <name>.sh # 通过 officecli CLI 二进制
python3 <name>.py # 通过 officecli Python SDK(pip install officecli-sdk)
两者重新生成同一份输出文档。下面按文档类型给出示例清单(展示其中一种形式,bash ….sh 与 python3 ….py 可随意互换)。
Word(.docx):
cd word
bash run-formatting.sh # Run/字符格式化:粗体/下划线/删除线/大小写/上下标/字体/效果
bash paragraph-formatting.sh # 段落格式化:对齐/缩进/间距/分页/底纹/markRPr
bash formulas.sh # LaTeX 数学公式
bash tables.sh # 样式化表格
bash textbox.sh # 格式化文本框
bash numbering.sh # 列表/编号样式
bash revisions.sh # 修订(tracked-change)API —— ins/del/format/move/cellChange
Excel(.xlsx):
cd excel
python cell-formatting.py # 完整 cell 属性面:字体、填充、边框、数字格式、公式/链接
bash charts.sh # 图表总览(一个工作簿内 8 种图表类型)
bash charts/charts-basic.sh # 按类型的高层示例(任意 charts/charts-<type>.sh)
python charts/charts-line.py # 单类型示例(任意 charts/charts-<type>.py)
python pivot-tables.py # 数据透视表
PowerPoint(.pptx):
cd ppt
bash presentation.sh # Morph 过渡 / 完整 deck
bash animations.sh # 动画效果
python video.py # 视频嵌入
bash 3d-model.sh # 3D 模型嵌入
bash diagram.sh # Mermaid 图表 —— render=native(可编辑形状)+ render=image(PNG)
python charts/charts-column.py # PowerPoint 图表示例(任意 charts/charts-<type>.py)
bash tables/tables-basic.sh # 表格 —— 最小创建 + 填充
bash tables/tables-styled.sh # 9 种内置样式 + 斑马纹标志 + rowHeight/name=
bash tables/tables-merged.sh # gridSpan 水平合并
bash tables/tables-borders.sh # 逐边/逐单元格边框
bash tables/tables-rows-cols.sh # 增行/增列、逐行高度、gridSpan + merge.down
bash tables/tables-financial.sh # 端到端金融 deck
bash transitions/transitions-basic.sh # cut/fade/dissolve/flash + 'none' 清除
bash transitions/transitions-directional.sh # push/wipe/cover/uncover × 方向矩阵
bash transitions/transitions-shapes.sh # circle/diamond/wedge/wheel/zoom
bash transitions/transitions-bands.sh # blinds/strips/split/checker
bash transitions/transitions-dynamic.sh # 2010+ Exciting 画廊(vortex/flip/...)
bash transitions/transitions-modern.sh # 2013+ Exciting 画廊(pageCurl/airplane/origami/...)
bash transitions/transitions-random.sh # newsflash / random
bash transitions/transitions-timing.sh # speed、duration、advanceTime、advanceClick
bash transitions/transitions-morph.sh # 2016+ Morph 补间
bash shapes/shapes-basic.sh # 几何、填充、轮廓、旋转、基础效果
bash shapes/shapes-connectors.sh # 直线/肘形/曲线连接符 + 组合
bash shapes/shapes-effects.sh # autoFit、翻转、图片填充、3D、软边缘、链接、zorder
bash shapes/shapes-typography.sh # 间距、kern、大小写、RTL 方向、font.cs、lang
bash textboxes/textboxes-basic.sh # 对齐、项目符号、runs、逐脚本字体
bash textboxes/textboxes-advanced.sh # 逐段落覆盖、缩进、逐 run 排版
python pictures/pictures-basic.py # picture src/crop/rotation/links(需要 Pillow)
核心命令模式
示例脚本高度复用四种命令模式,理解它们即可看懂绝大多数 .sh/.py 脚本。
创建并填充(Create and Populate)
#!/bin/bash
set -e
FILE="document.docx"
officecli create "$FILE"
officecli add "$FILE" /body --type paragraph --prop text="Hello World"
officecli validate "$FILE"
create 依据扩展名决定文档类型(.docx / .xlsx / .pptx),add 在指定父路径下追加元素,validate 对照 OpenXML schema 做一致性检查——这是所有示例的标准收尾动作,例如 examples/word/formulas.sh 在末尾即执行 close + validate。
批量操作(Batch Operations)
cat << 'EOF' > commands.json
[
{"command":"add","parent":"/body","type":"paragraph","props":{"text":"Para 1"}},
{"command":"set","path":"/body/p[1]","props":{"bold":"true","size":"24"}}
]
EOF
officecli batch document.docx < commands.json
batch 从 stdin 读取 JSON 数组,每条都是一个 {"command", "parent"/"path", "type", "props"} 字典,与 Python SDK 的 doc.batch(<a href="https://link.gitcode.com/i/4b7d25db1031cdc2aaa2551473dec50a" target="_blank">...]) 完全同构。从源码看,[BatchExecutor.cs 与 CommandBuilder.Batch.cs 负责逐条解析并执行这批指令,遇到属性名无法识别时会给出明确的 UNSUPPORTED props 警告(退出码 2),examples/excel/charts.sh 就特意不设 set -e 以容忍这类前向兼容警告、继续构建完整文档。
常驻模式(Resident Mode,3 次以上操作)
officecli open document.docx
officecli add document.docx /body --type paragraph --prop text="Fast operation"
officecli set document.docx /body/p[1] --prop bold=true
officecli close document.docx
对同一文件执行 3 次以上操作时,open 把文档载入内存常驻进程,后续命令不再反复读写磁盘,close 时落盘释放。从源码结构看,ResidentClient.cs 与 ResidentServer.cs 实现了这条命名管道会话,ResidentFlushPolicy.cs 控制刷新策略。Python SDK 正是复用同一管道协议——sdk/python/README.md 说明它只做一件事:把命令字典转发给常驻进程,避免每次命令都拉起新进程,因此循环编辑比逐命令 shell 调用快数百倍。
查询与修改(Query and Modify)
# 找出所有 Heading1 段落
officecli query report.docx "paragraph[style=Heading1]" --json
# 修改它们的颜色
officecli set report.docx /body/p[1] --prop color=FF0000
query 使用 CSS 风格选择器定位元素(如 paragraph[style=Heading1]、cell[formula~=SUM]),--json 输出结构化结果便于管道处理;set 通过 /body/p[1] 这类路径精确修改。/body/p[1] 中的 [1] 是位置索引,元素路径与选择器是 OfficeCLI 两个并行的定位体系。
命令速查表
文档类型支持矩阵
| 格式 | 扩展名 | 创建 | 查看 | 修改 |
|---|---|---|---|---|
| Word | .docx | ✓ | ✓ | ✓ |
| Excel | .xlsx | ✓ | ✓ | ✓ |
| PowerPoint | .pptx | ✓ | ✓ | ✓ |
常用命令
| 命令 | 用途 | 示例 |
|---|---|---|
create |
创建空白文档 | officecli create file.docx |
view |
查看内容 | officecli view file.docx text |
get |
获取元素 | officecli get file.docx /body/p[1] |
set |
修改元素 | officecli set file.docx /body/p[1] --prop bold=true |
add |
添加元素 | officecli add file.docx /body --type paragraph |
remove |
删除元素 | officecli remove file.docx /body/p[5] |
query |
CSS 风格查询 | officecli query file.docx "paragraph[style=Normal]" |
batch |
批量操作 | officecli batch file.docx < commands.json |
validate |
检查 schema | officecli validate file.docx |
查看模式(View Modes)
| 模式 | 说明 | 用法 |
|---|---|---|
text |
纯文本 | officecli view file.docx text |
annotated |
带格式标注的文本 | officecli view file.docx annotated |
outline |
文档结构 | officecli view file.docx outline |
stats |
统计信息 | officecli view file.docx stats |
issues |
问题诊断 | officecli view file.docx issues |
html |
HTML 预览 | officecli view file.docx html |
svg |
SVG 预览 | officecli view file.docx svg |
forms |
表单域 | officecli view file.docx forms |
实战示例纵深:从四件套脚本看底层实现
Word:LaTeX 公式(formulas)
examples/word/formulas.md 与其 .sh/.py 孪生脚本共同展示了 docx equation 元素:用 LaTeX 语法写入 60+ 条公式,覆盖代数、微积分、线性代数、概率统计、数论、化学、物理与高级排版记号。其 CLI 形式的核心模式是:
officecli add formulas.docx /body --type equation --prop 'formula=x = \frac{-b \pm \sqrt{b^{2} - 4ac}}{2a}'
关键点在于 mode 属性:mode=display(默认)生成独立的块级 oMathPara 居中公式,mode=inline 则把公式作为 oMath 子元素嵌入所在段落的句子中间。脚本还演示了矩阵环境(pmatrix/vmatrix/bmatrix)、分段函数(cases)、自动尺寸定界符、\cancel/\cancelto、\boxed、\textcolor 彩色数学等高级 LaTeX 能力。Python 孪生脚本 examples/word/formulas.py 展示了同一批指令如何打包进单个 doc.batch([...]) 往返——这正是 sdk/python/README.md 中「没有第二套词汇」的设计:命令字典与 officecli batch 列表完全一致。
Excel:图表总览(charts)
examples/excel/charts.sh 在一个工作簿内构建 8 种图表:组合图、3D 柱状图、散点+趋势线、3D 饼图、气泡图、股票 OHLC、填充雷达图、多环环形图,分 4 张工作表组织(月度销售、分析数据、股票数据、能力评估)。脚本先用 officecli set 逐格写入带样式的表头(--prop fill=1F4E79 --prop font.color=FFFFFF --prop alignment.horizontal=center)与数据,再通过 add 挂载图表。注意 numFmt 的两种写法:'numFmt=#,##0' 千分位与 'numFmt=0.0"%"' 百分比格式,是 xlsx cell 属性面的典型用法。若需某种单一图表类型,examples/excel/charts/ 提供了 17 个按类型拆分的四件套示例(line、bar、pie、scatter、stock、waterfall、combo、histogram 等)。
PowerPoint:Mermaid 图表(diagram)
examples/ppt/diagram.sh 是 Mermaid 图表示例,演示三种渲染模式:
render=native—— 无浏览器依赖,生成可编辑的 PowerPoint 形状 + 连接符(支持 flowchart / graph 与 sequenceDiagram 两种类型),整图作为一个组合对象(/slide[N]/group[K])可整体寻址与移动;render=image—— 通过真实 mermaid.js(无头浏览器)生成高保真 PNG,覆盖全部 mermaid 类型,源码会写入 alt 文本;render=auto—— 默认值,浏览器可用时走 image,否则回退 native。
该脚本特意 export OFFICECLI_NO_AUTO_RESIDENT=1 关闭自动常驻:render=image 会启动浏览器耗时数秒,逐条命令以独立进程运行可避免与常驻进程的单命令管道争用(Python 孪生则保留常驻,其客户端会重试忙碌连接)。源码来源 mermaid=(标准)、text=、dsl=、src=(指向 .mmd 文件,脚本中的 pie.mmd 即此类)四种可互换;x/y/width/height 定义放置框,图表按比例适配并居中。
实用技巧
-
修改前先探索:
officecli view document.docx outline officecli get document.docx /body --depth 2outline视图快速把握结构,get --depth 2查看两级子树。 -
自动化用
--json:officecli query data.xlsx "cell[formula~=SUM]" --json | jq结构化输出可直接喂给后续管道或 Agent。
-
用
help查属性(schema 参考内置于help动词之下):officecli help docx set paragraph officecli help xlsx set cell officecli help pptx set shape仓库 schemas/help/ 目录中存放着对应的机器可读 schema JSON(如 docx/paragraph.json 定义了 paragraph 的全部可设属性、别名与示例),
--json可输出原始 schema。 -
修改后验证:
officecli validate document.docx -
批量操作使用常驻模式(同一文件 3 次以上操作时):
officecli open file.pptx # ... 多条命令 ... officecli close file.pptx
贡献新示例
遵循以下步骤即可为仓库贡献示例:
- 编写带清晰注释的脚本
- 测试并验证输出
- 放入合适的目录(word/excel/ppt)
- 更新对应目录的 README
- 提交 PR
推荐的示例脚本模板:
#!/bin/bash
# 简要说明本示例演示的内容
# 关键技术:在此列出
set -e
FILE="output.docx"
officecli create "$FILE"
# ... 你的命令 ...
officecli validate "$FILE"
echo "Created: $FILE"
帮助系统与更多资源
顶层帮助:
officecli --help # CLI 用法
officecli help # Schema 参考入口
officecli help docx # 全部 docx 元素
officecli help docx set # docx 中支持 `set` 的元素
officecli help docx set paragraph # paragraph 可设属性
officecli help docx paragraph --json # 原始 schema JSON
officecli help all # 平铺输出全部(格式、元素、属性)
格式别名:word→docx、excel→xlsx、ppt/powerpoint→pptx;动词:add、set、get、query、remove。
深入资料方面,SKILL.md 是为 AI Agent 准备的完整命令参考(含 L1 读取 → L2 DOM 编辑 → L3 原始 XML 的三层策略与常驻模式说明),README.md 提供项目总览与安装方式;若要做整场 PPT 模板生成,可参考 examples/ppt/templates/README.md 与 skills/morph-ppt/SKILL.md;插件扩展能力见 plugins/plugin-protocol.md。
结语
examples/ 目录是 OfficeCLI 能力的完整标本库:每个示例的 .md 讲解 + .sh/.py 双构建脚本 + 预生成产物,让「读懂 → 复跑 → 改造」三步走没有任何障碍。无论你是想给 Agent 装配 Office 自动化能力、用 CLI 脚本批量生成报表,还是用 Python SDK 在服务端流水线中产出文档,都能在 examples/word/、examples/excel/、examples/ppt/ 中找到可直接复用或改造的实战模板。从公式排版到数据透视表,从 Morph 过渡到 3D 模型嵌入,跑一遍这些示例,就是掌握 OfficeCLI 全部能力的最快路径。