远程控制或脚本打开 Office 从 Python 编辑 Word 文档

2024-05-10

我想(最好在 Windows 上)在特定文档上启动 Open Office,搜索固定字符串并将其替换为我的程序选择的另一个字符串。

我该如何从外部 Python 程序中做到这一点? OLE-什么?原生 Python 脚本解决方案?

(The document is in the Word 97-2003 format, but that is probably not relevant?)


我会说使用Python-UNO 桥 http://udk.openoffice.org/python/python-bridge.html。这对你有用吗?

import uno

ctx = uno.getComponentContext()
service_manager = ctx.getServiceManager() 
desktop = service_manager.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
document = desktop.loadComponentFromURL("file:///file.doc", "_blank", 0, ())

replace_desc = document.createReplaceDescriptor() 
replace_desc.setSearchString("text_to_replace") 

find_iter = document.findFirst(replace_desc)
while find_iter:
    find_iter.String = "replacement_text"
    find_iter = document.findNext(find_iter.End, replace_desc)

See the X可搜索文档 http://api.openoffice.org/docs/common/ref/com/sun/star/util/XSearchable.html有关搜索的详细信息。另外,请确保使用以下命令行启动 OpenOffice:swriter "-accept=socket,host=localhost,port=2002;urp;".

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

远程控制或脚本打开 Office 从 Python 编辑 Word 文档 的相关文章

随机推荐