简体   繁体   中英

How can you extract the currently-selected range of cells in LibreOffice calc via pyuno?

When using pyuno in a LibreOffice / OpenOffice calc python macro, I would like simply to be able to select a range of cells, and when the macro is run, for all of the cell data (eg as some iterable object) to be able to be retrieved within the python script, so that it can be manipulated. I have found hardly any documentation on this, and would welcome some example code that demonstrates how to do this.

After a very painful time of trial and error (thanks to the scant documentation and examples on pyuno usage anywhere -- please correct me if I've overlooked something), I ended up with the following code that seems to do what I'm after:

import uno
doc = XSCRIPTCONTEXT.getDocument()

def mymodule():
    ctrlr = doc.CurrentController
    sel = ctrlr.getSelection()
    x = sel.getDataArray()
    # now the data is available as nested tuples in x, so do something with it
    file('/tmp/out', 'w').write(repr(x))

This can be put into a python file, and stored (at least with Ubuntu 14.04) in the ~/.config/libreoffice/4/user/Scripts/python directory, and then as long as the libreoffice-script-provider-python package is installed, it can be run from within LibreOffice Calc via the Tools->Macros->Run Macro menu option. Or it can be bound to a keyboard shortcut using the Tools->Customize->Keyboard dialog.

For a more complete example that allows one to load data from LibreOffice Calc into Octave for further analysis, see this pyuno script .

Or you could try something like this, which I think is more easily understood.

    desktop = XSCRIPTCONTEXT.getDesktop()
    model = desktop.getCurrentComponent()
    try:
        sheets = model.getSheets()
    except AttributeError:
        raise Exception("This script is for Calc Spreadsheets only")
    #sheet = sheets.getByName('Sheet1')
    sheet = model.CurrentController.getActiveSheet()
    oSelection = model.getCurrentSelection()
    oArea = oSelection.getRangeAddress()
    first_row = oArea.StartRow
    last_row = oArea.EndRow
    first_col = oArea.StartColumn
    last_col = oArea.EndColumn

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM