使用Python在Open Office中编写/读取数据数组 任何人有任何示例代码?

所以我编写了一个类,它使得使用Python与Excel或Gnumeric进行接口变得非常容易,并且希望将类扩展到包含Open Office。 我可以在30分钟内做到这一点,如果我只是有能力做到以下几点:

  • 在任意工作表和工作簿上设置一个值
  • 在任意表单和工作簿上获取单个值

如果这些很慢/有办法做到以下几点,我还需要能够:

  • 设置/获取数组'''
  • 设置/获得一个matrix'''

此外,创build和重命名表的能力会很好。

如果有人曾经在这方面做过工作,这是一个呐喊。 如果他们给我的信息,我会参考文件的顶部

我的项目可以在这里find: https : //sourceforge.net/projects/pyworkbooks/我鼓励你看看。

事实上,要通过Python访问OpenOffice或LibreOffice,必须经历从StarSuite时代inheritance的绝对不透明量的锅炉板块 – 从此以后从未正确logging(感觉)或简化。

我曾经讲过这个话题,为了找回演讲的部分内容,我用了40分钟的时间,开始了这个例子。

另一方面,它只适用于最新的LibreOffice版本 – 3.3 – 我相信它也适用于OpenOffice(但我不会build议任何人坚持OpenOffice,这是一个Oracle的死胡同)

下面的示例使用从“外部”连接到正在运行的LibreOffice实例的缓慢方法。 这是非常慢的 – 你将不得不参考如何使它在程序中“作为macros”工作的文档,以获得更好的性能。 (这样真的很慢)。

但是,这种方法允许您使用Pythonterminal和内省来探索开发人员可用的方法。

第一个不好logging的部分是,你必须启动Open / LibreOffice: soffice "-accept=socket,host=0,port=2002;urp;" 连接被接受。 然后,通过其接口创build一个新的电子表格,Office套件随附的python解释器运行以下代码(交互式或脚本):

 import uno import socket # only needed on win32-OOo3.0.0 # 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) # access the current writer document model = desktop.getCurrentComponent() try: sheets = model.getSheets() except Exception: raise TypeError("Model retrived was not a spreadsheet") sheet1 = getattr(sheets, sheets.ElementNames[0]) # At this point, you can use "dir" to check the methods and # attributes available for the sheet # the methots "getCellByPosition, to retrieve a cell object, # which has "getFormula" and "setFormula" # methods. for i in xrange(10): for j in xrange(10): cell = sheet1.getCellByPosition(i, j) cell.setFormula(str(i * j)) c1 = sheet1.getCellByPosition(1,1) 

正如你所看到的,这个连接部分是我在几年前到过的其他地方的样板,我怀疑任何活着的人能够find这样的东西的基本原理。 一旦你find“表”对象,对象的属性和方法开始变得有意义了。

有一个完整的在线开发者手册,甚至可以让人了解连接部分:

http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/OpenOffice.org_Developers_Guide

连接到LibreOffice(以及OpenOffice和StarOffice)的进程间API称为UNO。 它在LibreOffice API文档站点上有logging。

正如jsbueno所说,它期望守护进程正在运行与之通信。 启动守护进程的'soffice'命令的命令行参数决定了在UNO调用中需要提供的主机和端口值。

你也可以尝试ezodf这是我find的最好的pythonodf库

你可以使用pyoo 。 这是我对类似问题的回答https://stackoverflow.com/a/27082610/886607