您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在OpenOffice.Org Calc的单元格公式中调用Python宏?

如何在OpenOffice.Org Calc的单元格公式中调用Python宏?

在旧的OO.org论坛上,(超级)用户Villeroy发布了有关如何从OO.org Basic调用Python函数的说明,然后可将其用于公式中。关键是将com.sun.star.script.provider.MasterScriptProviderFactory服务用作桥梁。这是他的解决方案的改编版,可概括为在任意模块中调用任意函数

REM Keep a global reference to the ScriptProvider, since this stuff may be called many times: 
Global g_MasterScriptProvider as Object
REM Specify location of Python script, providing cell functions: 
Const URL_Main as String = "vnd.sun.star.script:" 
Const URL_Args as String = "?language=Python&location=user"

Function invokePyFunc(file AS String, func As String, args As Array, outIdxs As Array, outArgs As Array)
   sURL = URL_Main & file & ".py$" & func & URL_Args
   oMSP = getMasterScriptProvider()
   On Local Error GoTo ErrorHandler
      oScript = oMSP.getScript(sURL)
      invokePyFunc = oScript.invoke(args, outIdxs, outArgs)
      Exit Function
   ErrorHandler:
      Dim msg As String, toFix As String
      msg = Error$
      toFix = ""
      If 1 = Err AND InStr(Error$, "an error occurred during file opening") Then
         msg = "Couldn' open the script file."
         toFix = "Make sure the 'python' folder exists in the user's Scripts folder, and that the former contains " & file & ".py."
      End If
      Msg@R_389_2419@ msg & chr(13) & toFix, 16, "Error " & Err & " calling " & func
end Function

Function getMasterScriptProvider() 
   if isNull(g_MasterScriptProvider) then 
      oMasterScriptProviderFactory = createUnoService("com.sun.star.script.provider.MasterScriptProviderFactory") 
      g_MasterScriptProvider = oMasterScriptProviderFactory.createScriptProvider("") 
   endif 
   getMasterScriptProvider = g_MasterScriptProvider
End Function

然后可以使用它来创建可在公式中调用的OO.org Basic函数。使用示例pytype

Const libfile as String = "util"    REM functions live in util.py

Function pytype(value)
    pytype = invokePyFunc(libfile, "pytype", Array(value), Array(), Array())
End Function

一个可能的实现是创建一个Python加载项。但是,这是一个繁重的选择,因为它需要安装OpenOffice SDK,并且对于这种方法是适用于免费功能还是仅适用于类,这对我来说并不明显。

python 2022/1/1 18:40:27 有252人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶