Gar*_*erg 6 python excel openoffice-calc
所以我编写了一个类,它可以很容易地使用Python与Excel或Gnumeric进行交互,并且希望扩展该类以包含Open Office.如果我有能力执行以下操作,我可以在30分钟内完成此操作:
如果这些很慢/有办法做到以下几点,我还需要能够:
此外,创建和重命名工作表的能力也很棒.
如果有人之前已经开展过这项工作,这是一个呐喊.如果他们给我信息,我会在文件的顶部引用它们
我的项目可以在这里找到:https://sourceforge.net/projects/pyworkbooks/,我建议你看一下.
事实上,对于通过Python访问OpenOffice或LibreOffice,必须经历从StarOffice时代继承的绝对不透明数量的样板 - 从那以后从未正确记录(一种感觉)或简化.
我曾经讲过这个主题,我花了40分钟,只是为了找回我演讲的部分内容来设置下面的例子.
另一方面,它只使用了最新的LibreOffice版本 - 3.3 - 我相信它也适用于OpenOffice(但我不建议任何人坚持使用OpenOffice,这是Oracle死胡同)
下面的示例使用从"外部"连接到正在运行的LibreOffice实例的慢速方法.这非常慢 - 您必须参考有关如何使其作为宏从程序"内部"工作的文档,以获得更好的性能.(这种方式真的很慢).
但是,此方法允许您使用Python终端和内省探索开发人员可用的方法.
第一个记录不完整的部分是您必须启动Open/LibreOffice:
soffice "-accept=socket,host=0,port=2002;urp;"
用于接受连接.然后,通过其界面创建一个新的电子表格,并使用Office Suite附带的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)
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,这个连接部分是我多年前在其他地方找到的样板,我怀疑任何活着的人都能在这些东西中找到任何理由.但是,一旦你到达"sheet"对象,对象的属性和方法就开始变得有意义了.
在线有完整的开发人员手册,甚至可以让人们理解连接部分:
http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/OpenOffice.org_Developers_Guide