使用外部Python程序在OpenOffice中加载文档

6 投票
2 回答
3655 浏览
提问于 2025-04-15 18:35

我正在尝试创建一个Python程序(使用pyUNO),来对OpenOffice Calc表格进行一些修改。

我之前已经在“接受”模式下启动了OpenOffice,这样就可以从外部程序连接。看起来应该很简单:

import uno
# get the uno component context from the PyUNO runtime
localContext = uno.getComponentContext()

# create the UnoUrlResolver
resolver = localContext.ServiceManager.createInstanceWithContext(
                            "com.sun.star.bridge.UnoUrlResolver", localContext)

# connect to the running office
ctx = resolver.resolve("uno:socket,host=localhost,port=2002;"
                       "urp;StarOffice.ComponentContext")
smgr = ctx.ServiceManager

# get the central desktop object
DESKTOP =smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)

#The calling it's not exactly this way, just to simplify the code
DESKTOP.loadComponentFromURL('file.ods') 

但是当我尝试访问loadComponentFromURL时,出现了一个AttributeError错误。如果我执行dir(DESKTOP),我只看到以下属性和方法:

['ActiveFrame', 'DispatchRecorderSupplier', 'ImplementationId', 'ImplementationName',
'IsPlugged', 'PropertySetInfo', 'SupportedServiceNames', 'SuspendQuickstartVeto', 
'Title', 'Types', 'addEventListener', 'addPropertyChangeListener', 
'addVetoableChangeListener', 'dispose', 'disposing', 'getImplementationId', 
'getImplementationName', 'getPropertySetInfo', 'getPropertyValue', 
'getSupportedServiceNames', 'getTypes', 'handle', 'queryInterface', 
'removeEventListener', 'removePropertyChangeListener', 'removeVetoableChangeListener', 
'setPropertyValue', 'supportsService']

我读到在OpenOffice 3.0版本中有一个类似的错误(我现在使用的是OpenOffice 3.1,运行在Red Hat5.3上)。我尝试使用这里提到的解决方法,但似乎没有效果。

有没有什么想法?

2 个回答

4

我很久没用过PyUNO了,但回想起我在06年运行的代码,我是这样加载文档的:

def urlify(path):
     return uno.systemPathToFileUrl(os.path.realpath(path))

desktop.loadComponentFromURL(
        urlify(tempfilename), "_blank", 0, ())

你的例子是一个简化版,我不确定你是不是故意去掉了一些额外的参数。

如果没有loadComponentFromURL这个方法,那可能是API发生了变化,或者其他地方出了问题。我看过你的代码,感觉你做的事情和我当时做的差不多。

我觉得在桌面对象上用dir()方法得到的方法可能没什么用,因为我觉得这里用到了一个叫__getattr__的方法来处理请求,而你打印出来的所有方法都是用于com.sun.star.frame.Desktop这个占位对象的工具方法。

我觉得问题可能出在没有一个名为loadComponentFromURL的方法,它需要的参数数量正好是1个。也许如果你用4个参数的版本,方法就能被找到并使用。这可能只是Python和Java之间的一个不匹配,Java支持方法重载。

撰写回答