PyUno and calc/spreadsheet: how to export single sheet to csv?

28 Views Asked by At

I need to automate some spreadsheet manipulation and exporting via PyUNO, but I'm struggling on exporting a single sheet to CSV.

I made a simple shell script that first launch LibreOffice to open a given .xlsx file and then run a python3 script to execute all the needed logic.

Now I need to just export the current (ActiveSheet) to .csv but the PyUNO and OO UNO documentations are really terrible IMHO and I cannot find anything related to this.

Can anyone point me in the right direction?

Below is a simplified version of my script

import socket
import uno

def init():
    # 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()

    return model

model = init()

active_sheet = model.CurrentController.ActiveSheet

# business logic

# now I need to export active_sheet to .csv

Bonus question

How can I get the opened file name with PyUNO?

1

There are 1 best solutions below

3
Jim K On

Did you look at How to use python uno to open xls file and save as csv as UTF-8. The command to Export is storeToURL() (while storeAsURL() is like Save As) and the command to get the currently saved filename is getURL().

A search turned up this code which I will reproduce in full since it seems to be what you're looking for.

import os
import unicodedata

from com.sun.star.beans import PropertyValue


def csv_properties():
    '''Build the dialog parameter for UTF-8 CSV'''
    props = []
    p = PropertyValue()
    p.Name = 'FilterName'
    p.Value = 'Text - txt - csv (StarCalc)'
    props.append(p)
    p = PropertyValue()
    p.Name = 'FilterOptions'
    p.Value = '59,34,76,1,,0,false,true,true,false'
    props.append(p)
    return tuple(props)


def export_sheets_to_csv():
    '''Iter over each sheet and save it as CSV file. '''
    desktop = XSCRIPTCONTEXT.getDesktop()  # noqa
    model = desktop.getCurrentComponent()
    controller = model.getCurrentController()
    dirname = os.path.dirname(model.URL)
    for sheet in model.Sheets:
        controller.setActiveSheet(sheet)
        name = sheet.getName().lower().replace(' ', '-')
        name = unicodedata.normalize('NFKD', name).encode('ascii', 'ignore')
        filename = '{0}/{1}.csv'.format(dirname, name.decode('ascii'))
        model.storeToURL(filename, csv_properties())

g_exportedScripts = export_sheets_to_csv,