用本机 WPS Office 处理文档的命令行和 Python 库(macOS)。零依赖,一个 js 逃生口加十几个常用命令,输出 JSON。
自己从零写的,只为在终端和脚本里顺手,不追求跟别的项目兼容。
git clone https://github.com/gnehiur/wpsx.git ~/Documents/wpsx
cd ~/Documents/wpsx && uv venv && uv pip install -e .
ln -sf "$PWD/.venv/bin/wps" ~/.local/bin/wps
wps doctorwps doctor # WPS 装没装、跑没跑、驱动通不通、当前组件
wps ls # WPS 里打开着哪些文件
wps js 'Application.Documents.Count' # 任意 JS API;--use wps|et|wpp 先切组件;- 从 stdin 读
wps info a.docx b.xlsx c.pptx # 页数/字数/段落/表格;工作表;幻灯片数
wps text a.docx [-o a.txt] # 全文(文字、演示)
wps outline a.docx # 标题大纲
wps tables a.docx [-i 1] # 表格 → 二维数组
wps pdf a.docx b.xlsx c.pptx [-o 目录|文件]
wps convert txt a.docx # pdf docx doc txt rtf html | xlsx xls csv | pptx ppt
wps replace a.docx 旧=新 ... [--map JSON] [-o 另存] # 含页眉页脚,默认原地保存
wps fill 模板.docx name=张三 date=… -o 出.docx # {{key}} 占位符;报告没填上的
wps cells a.xlsx [A1:D10] [-s Sheet1] # 读区域(默认已用区域)
wps set a.xlsx A1=姓名 B2=90 'C3==SUM(B1:B2)' # 写单元格,= 开头是公式多个文件时输出 JSON 数组;任一失败退出码 1,错误在 stderr。WPSX_DEBUG=1 打印发给 WPS 的每条 JS。
from wpsx import WPS
with WPS() as w: # 一个会话跑到底,批量时用这个
for f in files:
w.pdf(f, out_dir)
w.fill("模板.docx", {"name": "张三"}, "out.docx")
w.js("return Application.ActiveDocument.Paragraphs.Count")w.with_doc(path, body_js, readonly=True, **vars):打开(或复用已打开的)文档,以 d 为对象执行函数体,自动关闭。所有命令都是它的十几行 JS。
- WPS for Mac 运行时在
~/Library/Containers/com.kingsoft.wpsoffice.mac/Data/下监听wpsdriverlocal_*Unix socket,仿 WebDriver 协议,POST /session/<id>/execute/script/evaluate执行 JS。Application是 WPS 的 JS API(对标 Word/Excel/PPT 对象模型),永远指向当前活动标签页的组件。 - 组件里没有打开的文档时无法
Open文件,所以工具会在~/Downloads/.wpsx/seeds/放空白种子文档让 WPS 打开,每个组件留一个_wpsx_seed_*标签页,这是正常的。 - WPS 打开文件时会自己跳到前台,
open -g拦不住。工具会记下原来最前面的应用,切换完立刻把焦点还回去;只有切换组件时才会发生,同一组件内连续操作不会。 - App Store 版 WPS 是沙盒应用,只能写
~/Downloads。往别处导出不是报错,是 WPS 直接崩溃。 因此输出一律先写~/Downloads/.wpsx/stage/再拷到目标;不在 Downloads 下的输入也先复制进去。中转文件保留 1 小时(WPS 崩溃恢复标签页时要能找到)。 - 已在 WPS 里打开的文件直接复用,不关你的窗口。
- 驱动接口无官方文档,WPS 大版本升级后可能变,
wps doctor会告诉你还通不通。 - 只在 App Store 版 WPS 12.1 上验证过。官网版若
doctor找不到驱动,先find ~/Library /tmp -name 'wpsdriverlocal_*',把找到的目录设为环境变量WPSX_SOCKET_DIR。 - 已知会让 WPS 崩溃、代码里刻意避开的:写 Downloads 之外;表格组件同时打开两个同名工作簿;循环给同一 Range 反复设字体。
Command-line tool and Python library that drives the locally installed WPS Office on macOS through its built-in automation driver (a WebDriver-like service on a Unix socket that evaluates WPS JS API scripts). Zero dependencies. Converts Word/Excel/PowerPoint to PDF with WPS's own layout engine, extracts text/outline/tables, find-and-replace, fills {{key}} templates, reads/writes cells, and exposes the whole WPS JS API via wps js. Handles the App Store sandbox (only ~/Downloads is writable) transparently. See the Chinese sections above for the command list; wps --help works too.
MIT,见 LICENSE。