Developing Python Macros for LibreOffice

References:

A. http://christopher5106.github.io/office/2015/12/06/openoffice-libreoffice-automate-your-office-tasks-with-python-macros.html


B. https://www.makeuseof.com/tag/install-pip-for-python/


1. LibreOffice contains a relatively barebones implementation of Python (at this time, version 3.5.5). It is located in the directory


C:\Program Files\LibreOffice\program


Adding modules to python requires installing pip via get-pip.py (See Reference B). The PATH variable needs to be modified to add the directory where pip was installed. In my specific case, it would be


PATH=%PATH%;C:\Program Files\LibreOffice\program\python-core-3.5.5\Scripts\


After writing my first macro, I moved it into the directory where the example python macros are stored


C:\Program Files\LibreOffice\share\Scripts\python


If there are no problems, you will see its entry in the Macro Organizer menu and when you click on it, the Run button should be enabled. If the button is greyed out, there is a python error in the macro. Unfortunately, debugging is difficult because the scripting context used in macros isn't available outside of that environment. I had to modify the macro to run from C:\Program Files\LibreOffice\program and connect to LibreOffice (as explained in Reference A) through


"C:\\Program Files (x86)\LibreOffice 5\program\soffice.exe" --calc --accept="socket,host=localhost,port=2002;urp;"


Once the macro runs from the Macro Organizer, I was able to embed it in a spreadsheet (as explained in Reference A). To do this, include_macro.py, the macro, and the spreadsheet need to be in


C:\Program Files\LibreOffice\program


Modify include_macro.py to replace PingPong.py with the correct name of the macro and issue the command


python include_macro.py <SpreadsheetName.ods>


After execution, the last line should read something like


File created: with_macro/<SpreadsheetName.ods>


The modified spreadsheet containing the macro will be located in the directory C:\Program Files\LibreOffice\program\with_macro