介绍
# WPS/Word Automation (Windows)
使用附带的 Python 脚本通过 COM 控制 Word 或 WPS。
## 前置要求
- 已安装 **Microsoft Word** 或 **WPS Writer** 的 Windows 系统。 - Python + **pywin32** (`python -m pip install pywin32`)。
## 快速开始
```bash python {baseDir}/scripts/wps_word_automation.py read --input "C:\path\file.docx" python {baseDir}/scripts/wps_word_automation.py replace --input "C:\path\file.docx" --find "旧" --replace "新" --save "C:\path\out.docx" python {baseDir}/scripts/wps_word_automation.py export --input "C:\path\file.docx" --format pdf --output "C:\path\out.pdf" ```
## 命令
### read
提取纯文本。
```bash python {baseDir}/scripts/wps_word_automation.py read --input "C:\path\file.docx" --output "C:\path\out.txt" ```
### replace
查找/替换文本。
```bash python {baseDir}/scripts/wps_word_automation.py replace --input "C:\path\file.docx" --find "old" --replace "new" --save "C:\path\out.docx" ```
### insert
在开头/结尾插入文本。
```bash python {baseDir}/scripts/wps_word_automation.py insert --input "C:\path\file.docx" --text "Hello" --where start --save "C:\path\out.docx" ```
### headings
对匹配的行应用标题 1/2/3 样式。
```bash python {baseDir}/scripts/wps_word_automation.py headings --input "C:\path\file.docx" --level 1 --prefix "# " --save "C:\path\out.docx" ```
### header-footer
设置页眉/页脚文本。
```bash python {baseDir}/scripts/wps_word_automation.py header-footer --input "C:\path\file.docx" --header "标题" --footer "页脚" --save "C:\path\out.docx" ```
### page-break
在末尾插入分页符。
```bash python {baseDir}/scripts/wps_word_automation.py page-break --input "C:\path\file.docx" --save "C:\path\out.docx" ```
### merge
将多个文档合并为一个。
```bash python {baseDir}/scripts/wps_word_automation.py merge --inputs "a.docx" "b.docx" --output "merged.docx" ```
### split
按页码范围拆分(例如 "1-3,4-6")。
```bash python {baseDir}/scripts/wps_word_automation.py split --input "C:\path\file.docx" --pages "1-3,4-6" --outdir "C:\out" ```
### export
导出为 PDF 或 TXT。
```bash python {baseDir}/scripts/wps_word_automation.py export --input "C:\path\file.docx" --format pdf --output "C:\path\out.pdf" python {baseDir}/scripts/wps_word_automation.py export --input "C:\path\file.docx" --format txt --output "C:\path\out.txt" ```
### image
在末尾添加或替换图片。
```bash python {baseDir}/scripts/wps_word_automation.py image --input "C:\path\file.docx" --image "C:\path\img.png" --save "C:\path\out.docx" ```
## 注意事项
- 如果安装了 WPS,请尝试 `--app wps`;否则默认使用 Word。 - 如果需要查看界面,请使用 `--visible true`。 - 避免批量使用;此技能适用于单文档操作。