2011-10-16 44 views
2

我想(最好在Windows上)在特定文檔上啓動Open Office,搜索固定字符串並將其替換爲我的程序選擇的另一個字符串。遠程控制或腳本打開Office以從Python編輯Word文檔

如何從外部Python程序那樣做? OLE-什麼?本地Python腳本解決方案?

(該文件是在以Word 97-2003格式,但是這可能是不相關?)

回答

3

我會說使用Python-UNO bridge。這對你有用嗎?

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) 

有關搜索的詳細信息,請參閱XSearchable docs。另外,請確保使用以下命令行啓動OpenOffice:swriter "-accept=socket,host=localhost,port=2002;urp;"

+0

有趣...會檢查。 –

+0

也許愚蠢的問題,但當Python說,ImportError:沒有模塊uno,我做錯了什麼?我安裝了標準的Windows 2.7.2 Python。 –

+0

它是OpenOffice的可選安裝組件。請參閱OpenOffice的Wiki中的[OOo上的Python簡介](http://wiki.services.openoffice.org/wiki/Using_Python_on_Windows)頁面以獲取安裝細節。 – jro