Jump to content

Python Guide - My First Macro

From The Document Foundation Wiki


Return to Index


My first Python Macro

All Python examples are stored as PC-based personal macros, as opposed to product Python scripts or document-based scripts. Any example in this guide assumes that you save in this place.

IMPORTANT Python's syntax is very strict, be sure copy and paste correctly.

Use your favorite text editor, or better an IDE to edit your code. Some guidelines for scripting and connecting with LibreOffice are here: Python Basics

For Writer

import uno

def my_first_macro_writer():
    doc = XSCRIPTCONTEXT.getDocument()
    text = doc.getText()  # com.sun.star.text.Text
    text.setString('Hello World in Python in Writer')
    return

For Calc

import uno

def my_first_macro_calc():
    doc = XSCRIPTCONTEXT.getDocument()
    cell = doc.Sheets[0]['A1']  # com.sun.star.sheet.XSpreadsheetDocument
    cell.setString('Hello World in Python in Calc')
    return


Execute macro

For Writer

  • Open Writer, go to Tools ▸ Macros ▸ Run macro... in section Library select mymacros (or your name file), in section Macro Name, select macro my_first_macro_writer and click in command button Run

Demo Writer

For Calc

  • Open calc, go to Tools ▸ Macros ▸ Run macro... in section Library select mymacros (or your name file), in section Macro Name, select macro my_first_macro_calc and click in command button Run

Demo Calc

Return to Index