在 Debian 上使用 LibreOffice 宏的完整指南
一 环境准备与安装
- 安装 LibreOffice 与 Python 宏支持(Debian 12 软件包名示例):
- sudo apt update
- sudo apt install -y libreoffice libreoffice-script-provider-python
- 如计划无界面运行或远程调用(UNO API),建议同时安装 UNO 运行时:
- sudo apt install -y libreoffice-ure libreoffice-base
- 说明:LibreOffice 支持 .odt/.ods/.odp 等开放文档格式,也可打开与保存 .docx/.xlsx/.pptx 等 Microsoft Office 格式,便于跨格式自动化处理。
二 宏的存放位置与组织方式
- 全局宏(所有用户可用):/usr/share/libreoffice/4/user/Scripts/(版本号可能不同,如 6、7)
- 用户宏(当前用户):~/.config/libreoffice/4/user/Scripts/(版本号可能不同)
- 目录结构建议:按语言/应用划分,例如:
- python/HelloWorld.py
- python/Writer/ReplaceText.py
- 宏文件命名:以 .py 结尾;模块名与文件名一致,函数作为宏入口(可被 LibreOffice 识别)。
三 编写并运行第一个 Python 宏
- 示例(Writer 文本替换,保存为 ~/.config/libreoffice/4/user/Scripts/python/Writer/ReplaceText.py):
-
from com.sun.star.beans import PropertyValue
def greet():
# 获取当前文本
document = XSCRIPTCONTEXT.getDocument()
text = document.getText()
cursor = text.createTextCursor()
text.insertString(cursor, “Hello, LibreOffice Python Macro!\n”, 0)
def replace_text(find, repl):
document = XSCRIPTCONTEXT.getDocument()
replace = document.createReplaceDescriptor()
replace.setSearchString(find)
replace.setReplaceString(repl)
# 简单全量替换(可按需设置更多属性:大小写、通配符等)
document.replaceAll(replace)
- 运行方式:
- 在 LibreOffice Writer 中:Tools → Macros → Run Macro,选择 Writer → ReplaceText → greet 或 replace_text。
- 首次运行若提示安全策略,请在 LibreOffice 中允许执行宏(见下一节)。
四 安全设置与常见问题
- 宏安全级别(GUI):Tools → Options → LibreOffice → Security → Macro Security
- 推荐选择:Medium(提示后运行)或 Low(信任已安装脚本);不建议 Very High(禁止运行)。
- 命令行无界面执行(UNO 连接示例):
- 启动服务:soffice --headless --accept=“socket,host=127.0.0.1,port=2002;urp;” --norestore &
- 说明:该方式便于在 Python/Celery 等服务中复用 LibreOffice 进程进行批量转换或宏调用(需自行实现 UNO 客户端)。
- 常见问题排查:
- 找不到 Python 宏:确认已安装 libreoffice-script-provider-python,并将脚本放在正确路径(含版本号目录)。
- 运行报错“找不到模块/属性”:确保使用 LibreOffice 内置的 Python UNO 环境(不要依赖系统 python3 直接运行),脚本中通过 XSCRIPTCONTEXT 获取文档对象。
- 宏未生效或安全拦截:在宏安全级别中降低限制并勾选信任对应脚本路径。