Python Guide - My First Macro

From The Document Foundation Wiki
Jump to navigation Jump to search


Return to Index

Other languages:
English • ‎español • ‎italiano • ‎português do Brasil • ‎日本語


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.

For Writer

1import uno
2
3def my_first_macro_writer():
4    doc = XSCRIPTCONTEXT.getDocument()
5    text = doc.getText()  # com.sun.star.text.Text
6    text.setString('Hello World in Python in Writer')
7    return

For Calc

1import uno
2
3def my_first_macro_calc():
4    doc = XSCRIPTCONTEXT.getDocument()
5    cell = doc.Sheets[0]['A1']  # com.sun.star.sheet.XSpreadsheetDocument
6    cell.setString('Hello World in Python in Calc')
7    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