事实上,要通过 Python 访问 OpenOffice 或 LibreOffice,必须经历从 StarOffice 时代继承而来的绝对不透明的样板文件——从那时起就从未正确记录(感觉)或简化。
我曾经讲过这个主题,我花了大约 40 分钟,只是为了检索我讲课的部分来设置下面的例子。
另一方面,它只适用于最新的 LibreOffice 版本 - 3.3 - 我相信它也适用于 OpenOffice(但我不建议任何人坚持使用 OpenOffice,此时它是 Oracle 的死胡同)
下面的示例使用从“外部”连接到正在运行的 LibreOffice 实例的慢速方法。这非常慢 - 您必须参考文档,了解如何从程序“内部”将其作为宏工作,以获得更好的性能。(这种方式真的很慢)。
但是,此方法允许您使用 Python 终端和自省来探索开发人员可用的方法。
第一个记录不佳的部分是您必须启动 Open/LibreOffice:
soffice "-accept=socket,host=0,port=2002;urp;"
接受连接。然后,通过其界面创建一个新的电子表格,并使用 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)
正如你所看到的,这部分的连接部分是我几年前在其他地方得到的样板,我怀疑任何活着的人都能从这些东西中找到任何理由。但是,一旦您深入了解“表格”对象,该对象上的属性和方法就开始变得有意义了。
在线有完整的开发人员手册,甚至可以让人们理解连接部分:
http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/OpenOffice.org_Developers_Guide