2016-04-14 30 views
1

我一直在尋找一些用戶友好的教程,但沒有運氣。LibreOffice的Python宏 - 替換文本中的字符串

我想在Python中爲LibreOffice編寫一個宏,它將取代Writer中當前打開的文檔中的字符串。令人驚訝的是,似乎沒有任何官方指南,文檔或示例,無論是來自開發人員還是用戶。

我需要知道的是,我該如何在Python中訪問當前打開文檔的文本並將其更改爲?工作的例子將是偉大的,但任何幫助非常感謝。

回答

3

一個簡單的 「Hello World」 的例子如下:

def hello(): 
    XSCRIPTCONTEXT.getDocument().getText().setString("Hello!") 

# Functions that can be called from Tools -> Macros -> Run Macro. 
g_exportedScripts = hello, 

https://wiki.openoffice.org/wiki/Python/Transfer_from_Basic_to_Python

如何搜索和替換文本取決於您的要求。替換一次或全部事件?用普通文本替換,還是替換表格,框架或標題等元素?區分大小寫,或者正則表達式?有關Basic中的示例,請參見Andrew Pitonyak's macro document中的第7.14節。

這裏是Python中的工作示例,改變所有的「搜索」,以「改變」:

document = XSCRIPTCONTEXT.getDocument() 
search = document.createSearchDescriptor() 
search.SearchString = "search for" 
search.SearchAll = True 
search.SearchWords = True 
search.SearchCaseSensitive = False 
selsFound = document.findAll(search) 
if selsFound.getCount() == 0: 
    return 
for selIndex in range(0, selsFound.getCount()): 
    selFound = selsFound.getByIndex(selIndex) 
    selFound.setString("change to") 
+0

你是我的英雄;)不僅代碼工作的承諾,但你所提供的鏈接也很棒!非常感謝你! – lsrom