[Solved] How to get named cells from external python

Creating a macro - Writing a Script - Using the API (OpenOffice Basic, Python, BeanShell, JavaScript)
Post Reply
salp
Posts: 2
Joined: Tue Jun 02, 2020 12:56 am

[Solved] How to get named cells from external python

Post by salp »

Hello, new to this forum and to OpenOffice.

I'm working on a python script that call's OO or LO Calc and needs to get all the named ranges from the spreadsheet.
So far the code below can to launch OO, attach to the current spreadsheet and read write to individual cells. The next step is to read all the named ranges.

I saw some macro examples, along the lines of
h = ThisComponent
for i in h.namedRanges:
print(i)

However in an external python script "h = ThisComponent" does not work, how do I perform this action in my code?
Or if anyone can point me to some documentation for embedding OO/LO into Python app.

Code: Select all

import sys
sys.path.append('/usr/lib/libreoffice/program')
import uno

import subprocess
run_soffice = [
            'soffice',
            '--accept=socket,host=localhost,port=2002;urp;StarOffice.Service',
            '--nologo',
            '--norestore',
        ]
subprocess.Popen(run_soffice)

localContext = uno.getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext)
ctx = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
smgr = ctx.ServiceManager
desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop",ctx)
model = desktop.getCurrentComponent()

active_sheet = model.CurrentController.ActiveSheet
cell1 = active_sheet.getCellRangeByName("C4")
cell1.String = "Hey , I'm working here!"

Thanks for the help.
Last edited by robleyd on Thu Jun 04, 2020 1:01 am, edited 1 time in total.
Reason: Tagged [Solved]
OpenOffice 4.1.7 on Linux Mint 19.3
FJCC
Moderator
Posts: 9547
Joined: Sat Nov 08, 2008 8:08 pm
Location: Colorado, USA

Re: how to get named cells from external python

Post by FJCC »

You should be able to use model instead of ThisComponent.

Code: Select all

oRanges = model.NamedRanges
And NamedRanges has a Count property that you can use to build the for loop.
OpenOffice 4.1 on Windows 10 and Linux Mint
If your question is answered, please go to your first post, select the Edit button, and add [Solved] to the beginning of the title.
salp
Posts: 2
Joined: Tue Jun 02, 2020 12:56 am

Re: How to get named cells from external python

Post by salp »

Thank you for the help, that works.
OpenOffice 4.1.7 on Linux Mint 19.3
Post Reply