実際のところ、Pythonを介してOpenOfficeまたはLibreOfficeにアクセスするには、StarOfficeの時代から受け継がれた完全に不透明な量のボイラープレートを通過する必要があります。
私はかつてこのテーマについて講義したことがあり、次の例を設定するために講義の一部を取得するために、almotを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)
ご覧のとおり、これの接続部分は、私が何年も前に入手した定型文であり、生きている人がそのようなものに何らかの論理的根拠を見つけることができるとは思えません。ただし、「sheets」オブジェクトにたどり着くと、オブジェクトの属性とメソッドが意味をなし始めます。
オンラインには完全な開発者マニュアルがあり、接続部分を理解することさえできます。
http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/OpenOffice.org_Developers_Guide