【问题标题】:Running Libreoffice BASIC macro from python从 python 运行 Libreoffice BASIC 宏
【发布时间】:2016-03-03 11:40:49
【问题描述】:

我在 LibreOffice BASIC 中有一个宏,我想从我的 python 程序中运行它。我发现了一些他们使用此代码的线程:

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 程序。可以这样做吗?

谢谢:)

【问题讨论】:

    标签: python macros libreoffice basic libreoffice-calc


    【解决方案1】:

    我首选的方法是将 python 脚本放在 LibreOffice user directory 的 Scripts/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 从 Writer 运行 python 脚本。展开 My Macros 并选择脚本的名称。

    另一种似乎更接近您的 Excel 示例的方法是使用系统调用启动 LibreOffice 的侦听实例:

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

    我通常在 shell 脚本(Windows 上的批处理文件)而不是 python 中执行该部分。然后在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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      • 1970-01-01
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多