Tuesday, July 6, 2010

Python and OpenOffice - Hello World

Recently I had the need to automate data gathering into an openoffice calc heet, after some frustration playing with the OO macro language (OOBasic) I did some research on how to interact with OO from Python. There is some documentation spread over wikis and forums but not that much so I am going to share my learning here.
This is a simple hello world script which will fill the "A1" Cell from the current active sheet with "Hello World" in bold.
Please note that I will be using regular python scripts launched from the terminal and which will interact with OO using a UNO socket bridge.
First you will need to start oocalc in listenting mode (to accept UNO connections), from the terminal:
oocalc "-accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager" -norestore -nofirststartwizard -nologo
Now just execute python and try the following code:
from uno import getComponentContext
from com.sun.star.awt.FontWeight import BOLD

# Connect to soffice using UNO
localContext = getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext)
context = resolver.resolve("uno:socket,host=localhost,port=%d;urp;StarOffice.ComponentContext" % 8100)

# Get desktop service
desktop = context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", context)

# Get current document
document = desktop.getCurrentComponent()

# Get the active sheet
sheet = desktop.getCurrentComponent().getCurrentController().getActiveSheet()

# Get the "A1" cell reference
cell = sheet.getCellRangeByName("A1")

# Set a string
cell.setString('Hello World')

# Change to bold
cell.CharWeight = BOLD


That is all for the first lesson :)

1 comment:

  1. Very good and important for Developers to know they have access to core OO.o with fine tools like the popular Python.

    Nice writeup!

    Dietrich T. Schmitz

    ReplyDelete