Run Python in Calc Through LibreOffice’s Macro System

If a Python script runs from your terminal but cannot read or change the spreadsheet open in Calc, it is probably running outside LibreOffice. A Calc Python macro needs to run inside the LibreOffice process, where LibreOffice supplies the active document context. Save the script as a module in your user Python scripts folder, export its function with g_exportedScripts, and launch it from Calc’s macro dialog.

This is the simplest path for a small automation tied to the open workbook. LibreOffice’s current Python scripting help describes both in-process macros and separately connected Python scripts; the steps below use the in-process method.

Why doesn’t a regular Python script see the open spreadsheet?

LibreOffice exposes the current document to a running Python macro through the global XSCRIPTCONTEXT. A script launched with your regular python command is a separate process, so that global is not automatically available. It can still communicate with LibreOffice, but that requires setting up a UNO connection to an already running office process. For a first macro, run the function inside LibreOffice instead.

A Python macro is a function in a .py module. The module’s g_exportedScripts tuple tells LibreOffice which functions to show in its macro list. These details are documented in LibreOffice’s Python programming reference.

How do you add a Python macro to Calc?

1. Find the user Python scripts folder

Use the personal My Macros location if you want a script that can run from any open LibreOffice document for your user account. LibreOffice documents the folder as %APPDATA%\LibreOffice\4\user\Scripts\python on Windows and $HOME/.config/libreoffice/4/user/Scripts/python on Linux and macOS. If the Scripts/python folders do not exist yet, create them. The script locations reference also explains the other macro containers: Application Macros and macros embedded in a document.

A Python file named hello_calc.py in LibreOffice’s user Scripts/python folder
Place the macro module in the user Scripts/python folder so LibreOffice can list it under My Macros.

Document macros are stored inside a particular file and are only accessible while that document is open. For a reusable personal utility, My Macros is usually easier to maintain. Avoid modifying LibreOffice’s application-wide macro folder, which may require administrator access.

2. Create and export a small test function

Open a plain-text editor, create hello_calc.py in the folder above, and add:

def hello_calc(*args):
    doc = XSCRIPTCONTEXT.getDocument()
    sheet = doc.Sheets[0]
    sheet.getCellRangeByName("A1").setString("Hello from Python")

g_exportedScripts = (hello_calc,)

The function gets the document currently connected to the macro call, selects its first sheet, and writes a harmless test string in A1. The final line is important: without the exported tuple, the function may not appear as a runnable macro. Save the file as plain text with the .py extension, not as a rich-text document or a file ending in .py.txt.

Python macro code using XSCRIPTCONTEXT and listing hello_calc in g_exportedScripts
The exported function uses XSCRIPTCONTEXT to access the open document and write a test value to cell A1.

LibreOffice supplies XSCRIPTCONTEXT to the macro module. It does not automatically pass that variable to modules imported by your code, so keep the first test self-contained. If you later split reusable functions into other modules, follow LibreOffice’s Python module import guidance.

3. Open a Calc file and run the exported function

  1. Open a test spreadsheet in Calc. Use a copy or a blank workbook while developing.
  2. Choose Tools > Macros > Run Macro.
  3. In the library list, expand My Macros, choose the Python module, and select hello_calc from the macro names.
  4. Click Run.

The same function can be started from the APSO extension, which LibreOffice recommends for in-process Python scripting and also provides a Python shell. You do not need APSO for the basic Run Macro flow described here.

LibreOffice macro selector with hello_calc highlighted under My Macros and the Run button visible
Choose the exported hello_calc function under My Macros, then run it from Calc.
LibreOffice Calc showing Hello from Python in selected cell A1
A visible value in A1 confirms the test macro reached the Calc document and changed a cell.

What if the macro is missing or appears to do nothing?

Work through these checks in order rather than changing broad security settings:

  • The module is not listed: confirm the file is in the exact user Scripts/python path, has a .py suffix, and contains a correctly spelled g_exportedScripts tuple. Reopen the macro dialog; if LibreOffice still does not list a newly added file, close and restart LibreOffice, then check again.
  • The macro name is missing: make sure the exported tuple includes the function object, for example (hello_calc,). The comma makes this a one-item Python tuple.
  • Nothing appears in the terminal: output from print() is not available when Python macros run from the standard macro dialog. The test above writes into A1 so the result is visible in the sheet. For interactive debugging, APSO’s shell displays output.
  • An import fails: installing a package for your system Python does not guarantee that LibreOffice’s Python runtime can import it. The package must be available on the runtime’s Python path; the official import guidance describes user and shared module paths. Start by testing the macro without optional imports.
  • A security warning appears: only run scripts you wrote or have reviewed and trust. Macro security exists to limit unsafe code; do not lower the global security level just to make an unfamiliar document’s macro run. Consult LibreOffice’s macro security options if you need to understand a warning.

Choose the external-process approach only when your automation must start from a terminal, scheduler, or another application. LibreOffice requires you to start the office process with a pipe or socket and connect through its UNO bridge; an ordinary standalone script is not equivalent to an in-process Calc macro.

How can you verify that the macro worked?

After clicking Run, look at cell A1 on the first sheet. It should contain Hello from Python, and the formula bar should show the same text when A1 is selected. If the cell remains unchanged, confirm that the intended workbook was active and that the macro was selected from My Macros. Once this minimal test succeeds, replace the test write with your real calculation and test it on a copy of the workbook before using it on important data.

Leave a Comment

Protect Selected Writer Text with a Section Password

Protect Selected Writer Text with a Section Password

Lock a specific passage against routine edits while keeping the rest of a Writer document usable, and learn when file encryption is the better choice.

Make Spreadsheet Text Readable in LibreOffice Calc Dark Mode

Make Spreadsheet Text Readable in LibreOffice Calc Dark Mode

Fix hard-to-see spreadsheet text by checking the theme, cell font color, fills, and conditional formatting in Calc.

LibreOffice Calc Shows Formulas as Text? Restore the Results

LibreOffice Calc Shows Formulas as Text? Restore the Results

Learn why Calc shows formula text instead of calculated values and fix display mode, Text-formatted cells, apostrophes, or stale results.

Merge Writer Letters with a Logo and Spreadsheet Fields

Merge Writer Letters with a Logo and Spreadsheet Fields

Build a reusable Writer mail merge with Calc recipient data and a shared embedded image, then preview and save the personalized letters.

Limit Optional Diagnostics and Update Data in LibreOffice

Limit Optional Diagnostics and Update Data in LibreOffice

Turn off LibreOffice’s optional update statistics and crash-report prompts, then check what the settings cover and how to verify them.

Use Regex in LibreOffice Writer to Edit Text in Batches

Use Regex in LibreOffice Writer to Edit Text in Batches

Clean spacing, find structured text, and rearrange names with Writer regex patterns you can preview before replacing.

Set Arabic and Hebrew Paragraphs to Right-to-Left in Writer

Set Arabic and Hebrew Paragraphs to Right-to-Left in Writer

Enable Writer’s bidirectional controls, set RTL paragraph flow, and check mixed Arabic or Hebrew text without disrupting English words and numbers.

Restore Calibri and Arial in LibreOffice Without Guesswork

Restore Calibri and Arial in LibreOffice Without Guesswork

Install metric-compatible Linux fonts or map LibreOffice fallbacks, while keeping Microsoft font licensing and layout differences in view.

Create Fillable PDFs from Forms in LibreOffice Writer

Create Fillable PDFs from Forms in LibreOffice Writer

Add usable text fields, check boxes, and drop-downs in Writer, then export a PDF recipients can complete and save.

Make LibreOffice PDFs Keep the Fonts You Used

Make LibreOffice PDFs Keep the Fonts You Used

Fix missing or substituted fonts in LibreOffice Writer PDFs, choose the right export profile, and verify which fonts are embedded before sharing.