Python and Open Office

Gary Herron gherron at islandtraining.com
Wed Sep 10 16:39:18 EDT 2008


Greg Lindstrom wrote:
> Hello,
>
> I would like to create and manipulate Open Office documents using 
> Python.  I have found then UNO Python page and odfpy modules which 
> seem to be exactly what I need.  The odfpy manual is, to me, a 
> confusing list of objects and methods (it's an impressive list!), but 
> does not have much in the way of how to use them.  For example, I can 
> open a spreadsheet and create new pages (there's a nice example near 
> the back of the manual) but I can't figure out how to open an existing 
> spreadsheet and list the names of the individual sheets ("tabs").
>
> I have written an application that access Microsoft Excel and creates 
> reports for work, but would like to create an Open Source version 
> using Open Office and release it to the community (and maybe get a 
> talk at PyCon :-).
>
> Is there someone here who can help me out, or is there an appropriate 
> mailing list for me to join? 
>
> Thanks
>
> --greg
> ------------------------------------------------------------------------
>
> --
> http://mail.python.org/mailman/listinfo/python-list

Here's a snippet of code I use to open a spreadsheet (given as a file 
path name), and compute and return the list of sheets it contains.  It 
connects to an existing OpenOffice if possible, otherwise it starts 
OpenOffice and waits for it to accept a connection.



def OpenSS(path):
    localContext = uno.getComponentContext()
    resolver = localContext.ServiceManager.createInstanceWithContext(
        'com.sun.star.bridge.UnoUrlResolver', localContext )

    
resolveArg='uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext'

    # Conect to running OO;  First, starting OO if necessary;
    try:
        ctx = resolver.resolve(resolveArg)
    except NoConnectException:
        os.system("ooffice '-accept=socket,host=localhost,port=2002;urp;'&")
        while 1:
            print '  waiting for OpenOffice'
            time.sleep(1)
            try:
                ctx = resolver.resolve(resolveArg)
                break
            except NoConnectException:
                pass
    smgr = ctx.ServiceManager
    desktop = smgr.createInstanceWithContext( 
'com.sun.star.frame.Desktop', ctx)

    url = 'file://' + path
    component = desktop.loadComponentFromURL(url, '_default', 0, ())
    sheets = [component.getSheets().getByIndex(i)
              for i in range(component.getSheets().getCount())]
    return sheets


Hope this helps,

Gary Herro





More information about the Python-list mailing list