2016-03-03 88 views
1

我在LibreOffice BASIC中有一個宏,我想從我的python程序運行它。我發現一些線程中,他們使用此代碼:從python運行Libreoffice BASIC宏

import os 
import win32com.client 

if os.path.exists("excelsheet.xlsm"): 
    xl=win32com.client.Dispatch("Excel.Application") 
    xl.Workbooks.Open(Filename="C:\Full Location\To\excelsheet.xlsm", ReadOnly=1) 
    xl.Application.Run("excelsheet.xlsm!modulename.macroname") 
## xl.Application.Save() # if you want to save then uncomment this line and change delete the ", ReadOnly=1" part from the open function. 
    xl.Application.Quit() # Comment this out if your excel script closes 
    del xl 

但是這是針對Windows的Excell程序,我想爲LibreOffice的程序。是否有可能做到這一點?

謝謝:)

回答

1

我的首選方法是把python腳本在LibreOffice user directory的腳本/ Python的子文件夾。然後在底部添加此功能:

def call_basic_macro(): 
    document = XSCRIPTCONTEXT.getDocument() 
    frame = document.getCurrentController().getFrame() 
    ctx = XSCRIPTCONTEXT.getComponentContext() 
    dispatcher = ctx.ServiceManager.createInstanceWithContext(
     'com.sun.star.frame.DispatchHelper', ctx) 
    url = document.getURL() 
    macro_call = ('macro:///Standard.Module1.Macro1("%s")' % url) 
    dispatcher.executeDispatch(frame, macro_call, "", 0,()) 

g_exported_scripts=call_basic_macro, 

現在,通過將Tools -> Macros -> Run Macro運行從作家的python腳本。展開My Macros並選擇腳本的名稱。

這似乎更接近您的Excel例如另一種方法是啓動的LibreOffice的聽實例與系統調用:

start soffice -accept=socket,host=0,port=2002;urp; 

我通常做一個shell腳本,部分(在Windows批處理文件),而不是蟒蛇。然後在python中,從實例中獲取文檔上下文:

import uno 
localContext = uno.getComponentContext() 

之後,代碼看起來與上面類似。請注意,在Windows上使用此方法時,必須使用LibreOffice附帶的python.exe才能加載uno模塊。

的第三種方法是簡單地做一個系統調用:

soffice "macro:///Standard.Module1.Macro1()" 

有關這方面的第三種方法,請參閱https://forum.openoffice.org/en/forum/viewtopic.php?f=20&t=8232