OpenOffice or LibreOffice ?

OpenOffice and LibreOffice are the master open up-source office suites, the opensource equivalent to Microsoft Office, to create text document, spreadsheets, presentations and drawings.

LibreOffice was a fork of OpenOffice.org (when OpenOffice went under Oracle's umbrella) and is built on the original OpenOffice.org code base.

Both are equivalent, but the usual propose is to employ LibreOffice (see the differences) since information technology is the projection of the volunteers from the open-source community and has been developping more quickly.

I'll speak most LibreOffice at present, simply the aforementioned is true for OpenOffice.

Download Libreoffice

and in the menu bar LibreOffice > Preferences, enable macros

macro_security

I would recommend you to ready Macro security to Medium which volition not block nor permit macros merely warning you to choose if you lot trust the editor of the document :

macro_security

Which language choice for writing your LibreOffice macros ?

Macros are scripting for the office suite.

Many languages are accepted by the LibreOffice API, thanks to the Universal Network Objects (UNO). Amid them are : Visual Basic, Coffee, C/C++, Javascript, Python.

The API is interface-oriented, meaning your code communicate with the controller of the interface and the certificate has to be open up. Many other Python libraries are not interface-oriented, creating directly the file in the Open up Document format and saving it to disk with the correct extension

  • .odt for text files
  • .ods for spreadsheets
  • .odp for presentations
  • .odg for drawings

For the choice of the linguistic communication, I would commencement insist on the multi-platform requirement, which means it'south better if the macro / script can be executed on different platforms such as Windows, Mac Bone or Linux, because LibreOffice is also multi-platform and documents will be shared between users from which nosotros cannot expect a particular platform. Visual Basic is non multi-platform and would require significant changes from one plateform to another (Visual Bones, Real Basic, AppleScript…).

Java and C/C++ require compilation, are much more circuitous and verbose.

For a scripting need, I would advise Javascript or Python. Both are very present in script development earth wide and are standards de facto. Many tools have been built for task automation on Javascript, such every bit Cordova (the multi-platform mobile app framework) or Grunt. Many other tools are using Python also, such as AWS CLI for example.

I would advise to write most of your code logic exterior the interface-orientated architecture, post-obit a standard lawmaking architecture, with your common NodeJS dependencies or Python libraries.

Only, Javascript could be not precise enough to work nicely in your spreadsheets (fifty-fifty though there exists very nice libraries for numeric computation) and could be disconcerting for your Office users due to rounding errors ( 0.1 + 0.2 does not equals 0.3 in Javascript).

On the reverse, Python has been used extensively for numeric computation, with famous libraries such as Numpy, Numexpr … which make it perfect for spreadsheet macros.

Python has besides numerous available libraries for other purposes, due to its success and support from big digital companies, such every bit Excel reading or writing libraries which brand it the perfect option for macro development.

Even though Python 2.7 still remains very used, and Python 3 introduced differences, the latest version of LibreOffice comes with Python 3.3, and then the use of Python three.3 is advised for immovability.

            /Applications/LibreOffice.app/Contents/MacOS/python              --version              #Python 3.3.five                      

First play with the Python shell to get familiar

Earlier creating your own macro, let's play with the Python shell and interact with a document, let's say a spreadsheet.

Kickoff launch LibreOffice Calc (Calc for spreadsheet open documents) with an open socket to communicate with from the crush on your Mac Bone :

            /Applications/LibreOffice.app/Contents/MacOS/soffice              --calc              \              --take              =              "socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"                      

(for the Windows command : "C:\\Program Files (x86)\LibreOffice v\program\soffice.exe" --calc --take="socket,host=localhost,port=2002;urp;" but if any problem, have a look the proposed workarounds).

and launch the Python shell

            /Applications/LibreOffice.app/Contents/MacOS/python                      

(for the Windows control : "C:\\Program Files (x86)\LibreOffice 5\program\python.exe").

Python-Uno, the library to communicate via Uno, is already in the LibreOffice Python's path.

To initialize your context, type the post-obit lines in your python crush :

                          import              socket              # only needed on win32-OOo3.0.0                            import              uno              # become the uno component context from the PyUNO runtime                            localContext              =              uno              .              getComponentContext              ()              # create the UnoUrlResolver                            resolver              =              localContext              .              ServiceManager              .              createInstanceWithContext              (              "com.sunday.star.bridge.UnoUrlResolver"              ,              localContext              )              # connect to the running office                            ctx              =              resolver              .              resolve              (              "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext"              )              smgr              =              ctx              .              ServiceManager              # go the central desktop object                            desktop              =              smgr              .              createInstanceWithContext              (              "com.sun.star.frame.Desktop"              ,              ctx              )              # access the current writer certificate                            model              =              desktop              .              getCurrentComponent              ()                      

These lines are common for every documents (Text, Spreadsheet, Presentation, Cartoon).

Now you can interact with the document.

Since we launched LibreOffice with --calc option, let'south attempt the spreadsheet interactions :

                          # access the active sail                            active_sheet              =              model              .              CurrentController              .              ActiveSheet              # access cell C4                            cell1              =              active_sheet              .              getCellRangeByName              (              "C4"              )              # prepare text inside                            cell1              .              String              =              "Hello world"              # other example with a value                            cell2              =              active_sheet              .              getCellRangeByName              (              "E6"              )              cell2              .              Value              =              cell2              .              Value              +              1                      

If you open a text document and access it with a new document author, you lot tin can attempt the following interactions :

                          # access the certificate's text property                            text              =              model              .              Text              # create a cursor                            cursor              =              text              .              createTextCursor              ()              # insert the text into the certificate                            text              .              insertString              (              cursor              ,              "How-do-you-do World"              ,              0              )                      

Here is a schema for what nosotros've just done : the shell communicates with the LibreOffice runtime to command actions inside the electric current document.

Python Uno mode ipc

Create your get-go macro

It is the other manner, the macro is called from inside the Libreoffice program :

Python Uno mode component

OpenOffice.org does not offering a style to edit Python scripts. You lot have to use your ain text editor (such as Sublim, Atom…) and your own commands.

There are 3 places where you can put your lawmaking. The first way is to add it equally a library for LibreOffice in ane of the directories in the PYTHONPATH

                          import              sys              for              i              in              sys              .              path              :              print              (              i              )                      

which gives

            /Applications/LibreOffice.app/Contents/Resources /Applications/LibreOffice.app/Contents/Frameworks /Applications/LibreOffice.app/Contents/Frameworks/LibreOfficePython.framework/Versions/3.3/lib/python3.3 /Applications/LibreOffice.app/Contents/Frameworks/LibreOfficePython.framework/Versions/iii.3/lib/python3.3/lib-dynload /Applications/LibreOffice.app/Contents/Frameworks/LibreOfficePython.framework/Versions/3.3/lib/python3.3/lib-tk /Applications/LibreOffice.app/Contents/Frameworks/LibreOfficePython.framework/Versions/iii.three/lib/python3.3/site-packages /Applications/LibreOffice.app/Contents/Frameworks/LibreOfficePython.framework/lib/python33.cipher /Applications/LibreOffice.app/Contents/Frameworks/LibreOfficePython.framework/lib/python3.three /Applications/LibreOffice.app/Contents/Frameworks/LibreOfficePython.framework/lib/python3.3/plat-darwin /Applications/LibreOffice.app/Contents/Frameworks/LibreOfficePython.framework/lib/python3.three/lib-dynload                      

But this is only useful to exist used in other macros.

The ii other means are to insert your script

  • either globally on your computer, in your local LibreOffice installation,

  • or within the certificate, so that when shared another computer (past email, or whatsoever means), the document has still functional macros.

Let'south run across how to install it in the LibreOffice install commencement, I'll show you the certificate-inside install in the adjacent department.

You can find and call your Macro scripts from the LibreOffice carte du jour for macros Tools > Macros > Organize Macros.

LibreOffice Python Macros

choosing Python :

LibreOffice Python Macro Directory

If yous become a "Coffee SE 6 Error bulletin" such equally blare

JavaSE6

download the Java SE 6 version here.

Allow's edit a starting time macro script file myscript.py that will print the Python version, creating a method PythonVersion :

                          import              sys              def              PythonVersion              (              *              args              ):              """Prints the Python version into the current document"""              #get the dr. from the scripting context which is made available to all scripts                            desktop              =              XSCRIPTCONTEXT              .              getDesktop              ()              model              =              desktop              .              getCurrentComponent              ()              #cheque whether there'south already an opened document. Otherwise, create a new i                            if              not              hasattr              (              model              ,              "Text"              ):              model              =              desktop              .              loadComponentFromURL              (              "private:manufacturing plant/swriter"              ,              "_blank"              ,              0              ,              ()              )              #go the XText interface                            text              =              model              .              Text              #create an XTextRange at the end of the document                            tRange              =              text              .              Terminate              #and set the string                            tRange              .              Cord              =              "The Python version is %s.%s.%s"              %              sys              .              version_info              [:              3              ]              +              " and the executable path is "              +              sys              .              executable              return              None                      

and copy it to the Macro directory for LibreOffice :

            cp myscript.py /Applications/LibreOffice.app/Contents/Resources/Scripts/python/                      

(under Windows it is C:\Program Files (x86)\LibreOffice five\share\Scripts\python directory).

Open up a new text certificate and run information technology from the menu :

LibreOffice Python Macro Directory

In instance at that place are multiple methods, all of them will exist exported, but nosotros can also specify which ane to export with the following statement at the end of the file :

                          g_exportedScripts              =              PythonVersion              ,                      

Its spreadsheet analogue would be :

                          import              sys              def              PythonVersion              (              *              args              ):              """Prints the Python version into the current document"""              #get the doc from the scripting context which is made available to all scripts                            desktop              =              XSCRIPTCONTEXT              .              getDesktop              ()              model              =              desktop              .              getCurrentComponent              ()              #check whether there's already an opened document. Otherwise, create a new one                            if              not              hasattr              (              model              ,              "Sheets"              ):              model              =              desktop              .              loadComponentFromURL              (              "private:factory/scalc"              ,              "_blank"              ,              0              ,              ()              )              #get the XText interface                            sail              =              model              .              Sheets              .              getByIndex              (              0              )              #create an XTextRange at the end of the certificate                            tRange              =              sheet              .              getCellRangeByName              (              "C4"              )              #and set the string                            tRange              .              Cord              =              "The Python version is %due south.%s.%south"              %              sys              .              version_info              [:              3              ]              #do the aforementioned for the python executable path                            tRange              =              sheet              .              getCellRangeByName              (              "C5"              )              tRange              .              String              =              sys              .              executable              return              None                      

For distribution of code, OXT format acts as containers of code that will exist installed by the Extension Manager or with the command line /Applications/LibreOffice.app/Contents/MacOS/unopkg.

A tutorial under Ubuntu

Other examples

Pack your script inside the document : the OpenDocument format

OpenDocument files are zipped directories.

You can have a await at inside by creating and saving a opendocument spreadsheet certificate with LibreOffice then unzipping information technology :

            unzip Documents/examination.ods -d test                      

You'll get the post-obit listing of files and subdirectories in your extracted file :

            ├── Configurations2 │   ├── accelerator │   │   └── current.xml │   ├── floater │   ├── images │   │   └── Bitmaps │   ├── menubar │   ├── popupmenu │   ├── progressbar │   ├── statusbar │   ├── toolbar │   └── toolpanel ├── META-INF │   └── manifest.xml ├── Thumbnails │   └── thumbnail.png ├── content.xml ├── manifest.rdf ├── meta.xml ├── mimetype ├── settings.xml └── styles.xml                      

Yous can directly append your script to the file with the zipfile library. Let's create include_macro.py :

                          import              zipfile              import              shutil              import              os              import              sys              print              (              "Delete and create directory with_macro"              )              shutil              .              rmtree              (              "with_macro"              ,              Truthful              )              os              .              mkdir              (              "with_macro"              )              filename              =              "with_macro/"              +              sys              .              argv              [              i              ]              impress              (              "Open file "              +              sys              .              argv              [              one              ])              shutil              .              copyfile              (              sys              .              argv              [              i              ],              filename              )              doctor              =              zipfile              .              ZipFile              (              filename              ,              'a'              )              md              .              write              (              "myscript.py"              ,              "Scripts/python/myscript.py"              )              manifest              =              []              for              line              in              doc              .              open              (              'META-INF/manifest.xml'              ):              if              '</manifest:manifest>'              in              line              .              decode              (              'utf-eight'              ):              for              path              in              [              'Scripts/'              ,              'Scripts/python/'              ,              'Scripts/python/myscript.py'              ]:              manifest              .              append              (              ' <manifest:file-entry manifest:media-type="awarding/binary" manifest:full-path="%due south"/>'              %              path              )              manifest              .              append              (              line              .              decode              (              'utf-8'              ))              dr.              .              writestr              (              'META-INF/manifest.xml'              ,              ''              .              join              (              manifest              ))              medico              .              close              ()              print              (              "File created: "              +              filename              )                      

such that to include your Python macro inside certificate.ods, just type command

            python include_macro.py certificate.ods                      

Later on enabling macros,

macro_document_alert

you should be able to run your macro

macro_document

Add a button control to launch your macro

Show the form control toolbar in the card View > Toolbars > Form Controls, activate Blueprint fashion (first red arrow) and add a button (2d reddish arrow) :

libreoffice form control

Right click on the push button to open the control properties and link with your macro :

libreoffice form control with macro

Toggle design way to OFF, close your toolbars. Your document is ready.

You tin can download my example hither. This document can be used to check everything works as espected on the LibreOffice version of your customer.

You can also add the button programmatically :

                          sheet              =              model              .              Sheets              .              getByIndex              (              0              )              LShape              =              model              .              createInstance              (              "com.sunday.star.drawing.ControlShape"              )              aPoint              =              uno              .              createUnoStruct              (              'com.sun.star.awt.Signal'              )              aSize              =              uno              .              createUnoStruct              (              'com.sun.star.awt.Size'              )              aPoint              .              X              =              500              aPoint              .              Y              =              1000              aSize              .              Width              =              5000              aSize              .              Superlative              =              1000              LShape              .              setPosition              (              aPoint              )              LShape              .              setSize              (              aSize              )              oButtonModel              =              smgr              .              createInstanceWithContext              (              "com.lord's day.star.form.component.CommandButton"              ,              ctx              )              oButtonModel              .              Proper name              =              "Click"              oButtonModel              .              Label              =              "Python Version"              LShape              .              setControl              (              oButtonModel              )              oDrawPage              =              sheet              .              DrawPage              oDrawPage              .              add together              (              LShape              )                      

and add a listener

                          aEvent              =              uno              .              createUnoStruct              (              "com.sun.star.script.ScriptEventDescriptor"              )              aEvent              .              AddListenerParam              =              ""              aEvent              .              EventMethod              =              "actionPerformed"              aEvent              .              ListenerType              =              "XActionListener"              aEvent              .              ScriptCode              =              "myscript.py$PythonVersion (document, Python)"              aEvent              .              ScriptType              =              "Script"              oForm              =              oDrawPage              .              getForms              ().              getByIndex              (              0              )              oForm              .              getCount              ()              oForm              .              registerScriptEvent              (              0              ,              aEvent              )                      

or

                          import              unohelper              from              com.sun.star.awt              import              XActionListener              course              MyActionListener              (              unohelper              .              Base              ,              XActionListener              ):              def              __init__              (              self              ):              impress              (              "ok1"              )              def              actionPerformed              (              self              ,              actionEvent              ):              print              (              "ok2"              )              doc              =              model              .              getCurrentController              ()              doc              .              getControl              (              oButtonModel              )              doc              .              getControl              (              oButtonModel              ).              addActionListener              (              MyActionListener              ())                      

Start a macro when document starts / opens / is loaded

In the toolbar Tools > Customize, add the macro :

python macro on start

Y'all have the pick to save the preference

  • either in the certificate itself, in this case the macro will exist executed whenever the certificate is opened on whatever calculator

  • or in the LibreOffice install on your local computer, in this instance the macro will be executed for every opened document.

Add together a listener when the cell content changes

                          import              uno              ,              unohelper              from              com.dominicus.star.util              import              XModifyListener              doc              =              XSCRIPTCONTEXT              .              getDocument              ()              #get your sail and cell                            cell              =              ..              course              myChange              (              XModifyListener              ,              unohelper              .              Base of operations              ):              def              __init__              (              self              ,):              cocky              .              doc              =              None              def              setDocument              (              self              ,              doc              ):              self              .              doc              =              physician              def              modified              (              self              ,              oEvent              ):              yourFunction              ()              def              disposing              (              self              ,              oEvent              ):              pass              def              AddMyListener              :              g              =              myChange              ()              grand              .              setDocument              (              doc              )              jail cell              .              addModifyListener              (              m              )              g_ImplementationHelper              =              unohelper              .              ImplementationHelper              ()              g_ImplementationHelper              .              addImplementation              (              myChange              ,              'com.sun.star.util.XModifyListener'              ,()              )              g_exportedScripts              =              AddMyListener              ,                      

Spreadsheet methods

Go a sheet

sheet = model.Sheets.getByName(sheet_name)

sheet = model.Sheets.getByIndex(0)

model.getCurrentController.setActiveSheet(sheet) prepare the sheet active

Protect / unprotect a canvass

canvas.protect(countersign)

sheet.unprotect(password)

sheet.isProtected()

Get a cell

sheet.getCellByPosition(col, row)

canvass.getCellRangeByName("C4")

Go cell range

sheet.getCellRangeByName("C4:x")

sheet.getCellRangeByName("C4:D10")

Go cell value

prison cell.getType() cell type (in from com.sun.star.table.CellContentType import TEXT, EMPTY, VALUE, FORMULA)

cell.getValue() or cell.Value

jail cell.getString() or prison cell.String

jail cell.getFormula() or cell.Formula

You lot can also accept a look at number formats, dates, …

Ready cell value

cell.setValue(value) or cell.Value=value

cell.setString(string) or prison cell.String=string

cell.setFormula(formula) or prison cell.Formula=formula (example : prison cell.setFormula("=A1"))

Cell background color (hexadecimal)

cell.CellBackColor=-1 (no color)

jail cell.CellBackColor=0 (black)

cell.CellBackColor=255 (blue)

prison cell.CellBackColor=0xFF0000 (red)

Become range value as an array

range.getDataArray()

Certificate Path

model.URL

                          import              bone              if              os              .              proper noun              ==              "nt"              :              directory              =              os              .              path              .              dirname              (              unohelper              .              fileUrlToSystemPath              (              model              .              URL              ))              else              :              directory              =              bone              .              path              .              dirname              (              model              .              URL              )[              7              :]                      

Named Ranges

Named ranges are like "allonym" or shortcuts defining ranges in the document :

libreoffice named ranges

Set a named range :

                          oCellAddress              =              active_sheet              .              getCellRangeByName              (              "C4"              ).              getCellAddress              ()              model              .              NamedRanges              .              addNewByName              (              "Test Proper noun"              ,              "C4"              ,              oCellAddress              ,              0              )                      

Get named range :

model.NamedRanges.getByName("Test Name")

libreoffice_names

List named ranges :

model.NamedRanges.getElementNames()

Exam named range :

model.NamedRanges.hasByName("dirs")

Remove a named range :

model.NamedRanges.removeByName('dirs')

get cell cavalcade and row

jail cell.getCellAddress().Cavalcade

cell.getCellAddress().Row

get cell canvas

cell.getCellAddress().Sail

go range column and rowstart/cease start/end/count

cell/range.getRangeAddress().StartRow

cell/range.getRangeAddress().StartColumn

cell/range.getRangeAddress().EndRow

cell/range.getRangeAddress().EndColumn

range.Rows.getCount() number of rows

range.Columns.getCount() number of columns

range.getCellFormatRanges()

clear contents

range.clearContents(4) clears the cells with a String as value other clearing flags

delete rows

sheet.getRows().removeByIndex(start_row,nb_rows)

Data pilots (equivalent to Excel'due south information pivots)

canvas.getDataPilotTables()

datapilot = sail.getDataPilotTables().getByIndex(0)

datapilot.SourceRange

datapilot.SourceRange=

datapilot.DataPilotFields

sheet.DataPilotTables.getByIndex(0).refresh()

Shapes

canvass.DrawPage.getCount()

sail.DrawPage.getByIndex(0)

sheet.DrawPage.getByIndex(17).Visible=Imitation

Charts

Become the charts

oCharts = sheet.getCharts()

Change dataseries order :

                          oXChartType              =              oCharts              .              getByIndex              (              0              ).              getEmbeddedObject              ().              getFirstDiagram              ().              getCoordinateSystems              ()[              0              ].              getChartTypes              ()[              0              ]              oSeries              =              oXChartType              .              getDataSeries              ()              oNewSeries              =              ()              oNewSeries              =              (              oSeries              [              4              ],              oSeries              [              3              ],              oSeries              [              ii              ],              oSeries              [              one              ],              oSeries              [              0              ]              )              oXChartType              .              setDataSeries              (              oNewSeries              )                      

Change color and transparency :

                          oCharts              .              getByIndex              (              pi              ).              getEmbeddedObject              ().              getFirstDiagram              ().              getCoordinateSystems              ()[              0              ].              getChartTypes              ()[              0              ].              DataSeries              [              0              ].              Colour              =              int              (              "7030A0"              ,              sixteen              )              oCharts              .              getByIndex              (              pi              ).              getEmbeddedObject              ().              getFirstDiagram              ().              getCoordinateSystems              ()[              0              ].              getChartTypes              ()[              0              ].              DataSeries              [              0              ].              Transparency              =              fifty                      

Deal with enumerations

                          RangesEnum              =              active_sheet              .              getCellRangeByName              (              "C4"              ).              getCellFormatRanges              ().              createEnumeration              ()              while              RangesEnum              .              hasMoreElements              ():              orange              =              RangesEnum              .              nextElement              ()                      

Export as a CSV in UTF-8

                          struct3              =              uno              .              createUnoStruct              (              'com.lord's day.star.beans.PropertyValue'              )              struct3              .              Name              =              "FilterName"              struct3              .              Value              =              "Text - txt - csv (StarCalc)"              struct4              =              uno              .              createUnoStruct              (              'com.sun.star.beans.PropertyValue'              )              struct4              .              Proper noun              =              "FilterOptions"              struct4              .              Value              =              "59,34,76,one,,0,faux,true,true,false"                      

Current impress area

model.CurrentController.ActiveSheet.PrintAreas[0]

Save every bit PDF

                          import              uno              from              com.lord's day.star.beans              import              PropertyValue              properties              =              []              p              =              PropertyValue              ()              p              .              Name              =              'FilterName'              p              .              Value              =              'calc_pdf_Export'              backdrop              .              append              (              p              )              model              .              storeToURL              (              'file:///tmp/exam.pdf'              ,              tuple              (              properties              ))              #less verbose :                            model              .              storeToURL              (              'file:///tmp/test2.pdf'              ,              tuple              ([              PropertyValue              (              'FilterName'              ,              0              ,              'calc_pdf_Export'              ,              0              )]))                      

Add filter data options (bachelor options), such a page range :

                          fdata              =              []              fdata1              =              PropertyValue              ()              fdata1              .              Proper noun              =              "PageRange"              fdata1              .              Value              =              "2"              fdata              .              append              (              fdata1              )              args              =              []              arg1              =              PropertyValue              ()              arg1              .              Proper name              =              "FilterName"              arg1              .              Value              =              "calc_pdf_Export"              arg2              =              PropertyValue              ()              arg2              .              Name              =              "FilterData"              arg2              .              Value              =              uno              .              Any              (              "[]com.dominicus.star.beans.PropertyValue"              ,              tuple              (              fdata              )              )              args              .              append              (              arg1              )              args              .              append              (              arg2              )              model              .              storeToURL              (              'file:///tmp/exam.pdf'              ,              tuple              (              args              ))                      

or a selection of cells "$A$1:$B$3"

                          fdata              =              []              fdata1              =              PropertyValue              ()              fdata1              .              Name              =              "Pick"              oCellRange              =              param_sheet              .              getCellRangeByName              (              "$A$one:$B$3"              )              fdata1              .              Value              =              oCellRange              fdata              .              append              (              fdata1              )              args              =              []              arg1              =              PropertyValue              ()              arg1              .              Proper name              =              "FilterName"              arg1              .              Value              =              "calc_pdf_Export"              arg2              =              PropertyValue              ()              arg2              .              Name              =              "FilterData"              arg2              .              Value              =              uno              .              Whatever              (              "[]com.sun.star.beans.PropertyValue"              ,              tuple              (              fdata              )              )              args              .              append              (              arg1              )              args              .              append              (              arg2              )              model              .              storeToURL              (              'file:///tmp/exam.pdf'              ,              tuple              (              args              ))                      

Determining the used area

                          cursor              =              canvas              .              createCursor              ()              cursor              .              gotoStartOfUsedArea              (              False              )              cursor              .              gotoEndOfUsedArea              (              True              )              rangeaddress              =              cursor              .              getRangeAddress              ()                      

Create a bulletin box

                          from              com.sun.star.awt.MessageBoxType              import              MESSAGEBOX              ,              INFOBOX              ,              WARNINGBOX              ,              ERRORBOX              ,              QUERYBOX              from              com.lord's day.star.awt.MessageBoxButtons              import              BUTTONS_OK              ,              BUTTONS_OK_CANCEL              ,              BUTTONS_YES_NO              ,              BUTTONS_YES_NO_CANCEL              ,              BUTTONS_RETRY_CANCEL              ,              BUTTONS_ABORT_IGNORE_RETRY              from              com.sun.star.awt.MessageBoxResults              import              OK              ,              Aye              ,              NO              ,              Cancel              parentwin              =              model              .              CurrentController              .              Frame              .              ContainerWindow              box              =              parentwin              .              getToolkit              ().              createMessageBox              (              parentwin              ,              MESSAGEBOX              ,              BUTTONS_OK              ,              "Here the title"              ,              "Here the content of the message"              )              consequence              =              box              .              execute              ()              if              result              ==              OK              :              print              (              "OK"              )                      

returns the value.

Have a wait here as well.

Work on selections using the dispatcher

                          # admission the dispatcher                            dispatcher              =              smgr              .              createInstanceWithContext              (              "com.lord's day.star.frame.DispatchHelper"              ,              ctx              )              # access the document                            doc              =              model              .              getCurrentController              ()              # enter a string                            struct              =              uno              .              createUnoStruct              (              'com.sunday.star.beans.PropertyValue'              )              struct              .              Name              =              'StringName'              struct              .              Value              =              'How-do-you-do World!'              dispatcher              .              executeDispatch              (              doc              ,              ".uno:EnterString"              ,              ""              ,              0              ,              tuple              ([              struct              ]))              # focus / go to cell                            struct              =              uno              .              createUnoStruct              (              'com.sun.star.beans.PropertyValue'              )              struct              .              Name              =              'ToPoint'              struct              .              Value              =              'Sheet1.A1'              dispatcher              .              executeDispatch              (              md              ,              ".uno:GoToCell"              ,              ""              ,              0              ,              tuple              ([              struct              ]))              # drag and autofill                            struct              =              uno              .              createUnoStruct              (              'com.sun.star.beans.PropertyValue'              )              struct              .              Name              =              'EndCell'              struct              .              Value              =              'Sheet1.A10'              dispatcher              .              executeDispatch              (              physician              ,              ".uno:AutoFill"              ,              ""              ,              0              ,              tuple              ([              struct              ]))              # recalculate                            dispatcher              .              executeDispatch              (              doc              ,              ".uno:Calculate"              ,              ""              ,              0              ,              tuple              ([]))              # unDo                            dispatcher              .              executeDispatch              (              physician              ,              ".uno:Undo"              ,              ""              ,              0              ,              ())              # reDo                            dispatcher              .              executeDispatch              (              doc              ,              ".uno:Redo"              ,              ""              ,              0              ,              ())              # quit LibreOffice                            dispatcher              .              executeDispatch              (              md              ,              ".uno:Quit"              ,              ""              ,              0              ,              ())              # insert rows                            dispatcher              .              executeDispatch              (              doctor              ,              ".uno:InsertRows"              ,              ""              ,              0              ,              ())              # delete rows                            dispatcher              .              executeDispatch              (              md              ,              ".uno:DeleteRows"              ,              ""              ,              0              ,              ())              # insert columns                            dispatcher              .              executeDispatch              (              doc              ,              ".uno:InsertColumns"              ,              ""              ,              0              ,              ())              # delete columns                            dispatcher              .              executeDispatch              (              dr.              ,              ".uno:DeleteColumns"              ,              ""              ,              0              ,              ())              # re-create, cut, paste                            dispatcher              .              executeDispatch              (              doc              ,              ".uno:Re-create"              ,              ""              ,              0              ,              ())              dispatcher              .              executeDispatch              (              doctor              ,              ".uno:Cutting"              ,              ""              ,              0              ,              ())              dispatcher              .              executeDispatch              (              doc              ,              ".uno:Paste"              ,              ""              ,              0              ,              ())              # clear contents of column A                            struct              =              uno              .              createUnoStruct              (              'com.sun.star.beans.PropertyValue'              )              struct              .              Name              =              'Flags'              struct              .              Value              =              'A'              dispatcher              .              executeDispatch              (              doc              ,              ".uno:Delete"              ,              ""              ,              0              ,              tuple              ([              struct              ]))              # saveAs                            struct              =              uno              .              createUnoStruct              (              'com.lord's day.star.beans.PropertyValue'              )              struct              .              Proper noun              =              'URL'              struct              .              Value              =              'file:///Users/christopherbourez/Documents/test_save.ods'              dispatcher              .              executeDispatch              (              doc              ,              ".uno:SaveAs"              ,              ""              ,              0              ,              tuple              ([              struct              ]))              # open                            struct              =              uno              .              createUnoStruct              (              'com.dominicus.star.beans.PropertyValue'              )              struct              .              Name              =              'URL'              struct              .              Value              =              'file:///Users/christopherbourez/Documents/examination.ods'              dispatcher              .              executeDispatch              (              doctor              ,              ".uno:Open"              ,              ""              ,              0              ,              tuple              ([              struct              ]))                      

You tin can have a look at other actions such equally Protection, Abolish, TerminateInplaceActivation, InsertContents (with backdrop 'Flags','FormulaCommand','SkipEmptyCells','Transpose','AsLink','MoveMode' )

Have a look at the equivalent in Visual Basic.

Create a dialog

Let's create and open a dialog with a button push button and a label such equally :

macro dialog in python

(example from this thread)

                          # create dialog                            dialogModel              =              smgr              .              createInstanceWithContext              (              "com.sun.star.awt.UnoControlDialogModel"              ,              ctx              )              dialogModel              .              PositionX              =              10              dialogModel              .              PositionY              =              ten              dialogModel              .              Width              =              200              dialogModel              .              Top              =              100              dialogModel              .              Title              =              "Runtime Dialog Demo"              # create listbox                            listBoxModel              =              dialogModel              .              createInstance              (              "com.sun.star.awt.UnoControlListBoxModel"              )              listBoxModel              .              PositionX              =              x              listBoxModel              .              PositionY              =              v              listBoxModel              .              Width              =              100              listBoxModel              .              Height              =              xl              listBoxModel              .              Name              =              "myListBoxName"              listBoxModel              .              StringItemList              =              (              'a'              ,              'b'              ,              'c'              )              # create the button model and fix the properties                            buttonModel              =              dialogModel              .              createInstance              (              "com.sunday.star.awt.UnoControlButtonModel"              )              buttonModel              .              PositionX              =              l              buttonModel              .              PositionY              =              50              buttonModel              .              Width              =              fifty              buttonModel              .              Elevation              =              14              buttonModel              .              Name              =              "myButtonName"              buttonModel              .              Characterization              =              "Click Me"              # create the label model and set the backdrop                            labelModel              =              dialogModel              .              createInstance              (              "com.sun.star.awt.UnoControlFixedTextModel"              )              labelModel              .              PositionX              =              x              labelModel              .              PositionY              =              70              labelModel              .              Width              =              100              labelModel              .              Height              =              14              labelModel              .              Proper noun              =              "myLabelName"              labelModel              .              Label              =              "Clicks "              # insert the control models into the dialog model                            dialogModel              .              insertByName              (              "myButtonName"              ,              buttonModel              )              dialogModel              .              insertByName              (              "myLabelName"              ,              labelModel              )              dialogModel              .              insertByName              (              "myListBoxName"              ,              listBoxModel              )              # create the dialog control and set up the model                            controlContainer              =              smgr              .              createInstanceWithContext              (              "com.sun.star.awt.UnoControlDialog"              ,              ctx              )              controlContainer              .              setModel              (              dialogModel              )              oBox              =              controlContainer              .              getControl              (              "myListBoxName"              )              oLabel              =              controlContainer              .              getControl              (              "myLabelName"              )              oButton              =              controlContainer              .              getControl              (              "myButtonName"              )              oBox              .              addItem              (              'd'              ,              4              )              # create a peer                            toolkit              =              smgr              .              createInstanceWithContext              (              "com.sun.star.awt.ExtToolkit"              ,              ctx              )              controlContainer              .              setVisible              (              False              )              controlContainer              .              createPeer              (              toolkit              ,              None              )              # execute it                            controlContainer              .              execute              ()                      

but clicking does not execute anything. Let'south close information technology, add listeners to increase the characterization counter when clicking the button, and re-open the dialog :

                          import              unohelper              from              com.sunday.star.awt              import              XActionListener              grade              MyActionListener              (              unohelper              .              Base              ,              XActionListener              ):              def              __init__              (              cocky              ,              labelControl              ,              prefix              ):              cocky              .              nCount              =              0              cocky              .              labelControl              =              labelControl              cocky              .              prefix              =              prefix              def              actionPerformed              (              self              ,              actionEvent              ):              # increase click counter                            cocky              .              nCount              =              self              .              nCount              +              1              self              .              labelControl              .              setText              (              self              .              prefix              +              str              (              cocky              .              nCount              )              )              # add together the activeness listener                            oButton              .              addActionListener              (              MyActionListener              (              oLabel              ,              labelModel              .              Label              ))              oBox              .              addActionListener              (              MyActionListener              (              oLabel              ,              labelModel              .              Label              ))              # execute again                            controlContainer              .              execute              ()                      

And permit's delete

                          # dispose the dialog                            controlContainer              .              dispose              ()                      

Working with a class

Y'all might have created a listbox of name "Listbox"

libreoffice listbox python

and linked to data :

libreoffice listbox data

                          # get the canvass                            accueil_sheet              =              model              .              Sheets              .              getByName              (              "Accueil"              )              # access the draw page                            oDrawPage              =              accueil_sheet              .              DrawPage              # count the number of form                            oDrawPage              .              getForms              ().              getCount              ()              # get the list box of the control element                            ListBox              =              oDrawPage              .              getForms              ().              getByIndex              (              0              ).              getByName              (              "Listbox"              )              # get the list box item list                            ListBox              .              StringItemList              # go the listing box controller                            ListBoxCtrl              =              model              .              getCurrentController              ().              getControl              (              ListBox              )              # get the selected items:                            ListBoxCtrl              .              SelectedItems                      

If the list box view is not in the current active sail, yous can access it with :

                          for              i              in              range              (              1              ,              accueil_sheet              .              DrawPage              .              getCount              ()):              if              accueil_sheet              .              DrawPage              .              getByIndex              (              i              ).              Control              .              Proper noun              ==              "ListBox"              :              ListBoxCtrl              =              accueil_sheet              .              DrawPage              .              getByIndex              (              i              ).              Control                      

Delight do not hesitate to do your contributions to my tutorial.

Well done !