Dup Ver Goto 📝

BasicLibreofficePython

To
73 lines, 207 words, 1860 chars Page 'BasicLibreofficePython' does not exist.

Ubuntu: Install Python Script Provider

sudo apt install libreoffice-script-provider-python

Create Scripts

Put these in ~/.config/libreoffice/4/user/Scripts/python. Note that Scripts is capitalised, but everything else is in lowercase. (Gotta love the consistency here.)

Example 1

This is the basic example Chatgpt gives. Put this in e.g. ~/.config/libreoffice/4/user/Scripts/python/hello.py

import uno

def hello_calc():
    # Get the LibreOffice desktop context
    ctx = XSCRIPTCONTEXT.getComponentContext()

    # Get the current Calc document
    doc = XSCRIPTCONTEXT.getDocument()

    # Get the active sheet
    sheet = doc.CurrentController.ActiveSheet

    # Set value in A1
    cell = sheet.getCellRangeByName("A1")
    cell.String = "Hello from Python!"

Example 2

Again courtesy of Chatgpt.

import uno

def sum_two_cells():
    doc = XSCRIPTCONTEXT.getDocument()
    sheet = doc.CurrentController.ActiveSheet

    cell1 = sheet.getCellRangeByName("A1")
    cell2 = sheet.getCellRangeByName("A2")

    try:
        value1 = float(cell1.String)
        value2 = float(cell2.String)
        result = value1 + value2
    except ValueError:
        result = "Error: Non-numeric input"

    sheet.getCellRangeByName("A3").String = str(result)

Writer Example

import uno

def hello_writer():
    # Get the current Writer document
    doc = XSCRIPTCONTEXT.getDocument()
    text = doc.Text
    cursor = text.createTextCursor()

    # Insert plain text
    text.insertString(cursor, "Hello from Python in Writer!\n", False)

    # Insert bold text
    cursor.CharWeight = 150  # Bold
    text.insertString(cursor, "This is bold text.\n", False)

    # Insert italic text
    cursor.CharPosture = 2  # Italic
    text.insertString(cursor, "This is italic text.\n", False)