Remote control or script Open Office to edit Word document from Python

倖福魔咒の 提交于 2019-11-30 20:45:17

问题


I want to (preferably on Windows) start Open Office on a particular document, search for a fixed string and replace it with another string selected by my program.

How do I do that, from an external Python program? OLE-something? The native Python scripting solution?

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


回答1:


I'd say using the Python-UNO bridge. Does this work for you?

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 XSearchable docs for details on searching. Also, make sure to have OpenOffice started with the following command line: swriter "-accept=socket,host=localhost,port=2002;urp;".



来源:https://stackoverflow.com/questions/7783678/remote-control-or-script-open-office-to-edit-word-document-from-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!