OpenOffice/LibreOffice Calc Macros(5)

受不了,還是用「錄製巨集」的方式來寫,因為真的很多函數的用法都不容易找到,找到了,也需要測試測試再測試,太花時間。錄製出來的BASIC語法,基本上都是利用 Dispatcher 然後帶參數去告訴 calc 該做些什麼事情,所以像是在一個格子裡輸入文字,錄製出來的結果會是先 Goto 到指定的儲存格,然後再去填文字。
即便是如此,要轉換為 Python,也需要不少工夫。下面幾篇是我找到的資料,非常有參考價值,一般錄製出來的BASIC函式,這幾篇都有對應的 Python 可以用:

第一個取得 dispatcher 會遇到的 createUnoService ,實際上程式是這樣子的:
[python]
def createUnoService( cClass ):
“””A handy way to create a global objects within the running OOo.
“””
ctx = uno.getComponentContext()
smgr = ctx.ServiceManager
obj = smgr.createInstance( cClass )
return obj
[/python]

第二個是建立 com.sun.star.beans.PropertyValue ,程式是這樣子的:
[python]
args1 = uno.createUnoStruct( “com.sun.star.beans.PropertyValue” )
args1.Name = “ToPoint”
args1.Value = “$A$2”
[/python]

然後是 dispatcher.executeDispatch(),在錄製出來的巨集裡,第一個參數是叫做 document,這個其實是XSCRIPTCONTEXT.getDocument().getCurrentController().getFrame() ,真的是很長;第二個參數是動作字串;第3個跟第4個參數都沿用錄製出來的參數;最後一個參數才是問題,這個要傳 tuple 進去,而且要多加一個空的元素在後面,例如 (arg0,)。

組合上面提到的,要在一個 sheet 裡的 A2 填字串,就是這樣子:
[python]
# 取得必要的變數
doc = XSCRIPTCONTEXT.getDocument()
controller = doc.getCurrentController()
dispatcher = createUnoService(“com.sun.star.frame.DispatchHelper”)

# 到 A2
args1 = uno.createUnoStruct( “com.sun.star.beans.PropertyValue” )
args1.Name = “ToPoint”
args1.Value = “$A$2”
dispatcher.executeDispatch(controller.getFrame(), “.uno:GoToCell”, “”, 0,
(args1,))

# 填字串
args2 = uno.createUnoStruct( “com.sun.star.beans.PropertyValue” )
args2.Name = “StringName”
args2.Value = “2012/4/12”
dispatcher.executeDispatch(controller.getFrame(), “.uno:EnterString”, “”,
0, (args2,))
[/python]

找的時候,有找到一篇 oosheet,這個 module 把 calc sheet 的相關部分都包起來了,看起來很好用,晚點來研究看看。