This isn’t a question, so much as it’s a solution that I believe will help others.
I crafted it partly by using chatgpt and scouring documentation on how to write scripts with python.
This is the result. I hope it helps somebody out there.
import uno
# Get the uno component context from the PyUno runtime
localContext = uno.getComponentContext()
# Get the uno service manager from the context
smgr = localContext.ServiceManager
# Get the desktop object
desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", localContext)
from subprocess import run, PIPE
# Translates a string from German to English using the CLI tool `crow`.
def translateText(de_string):
if not isinstance(de_string, str):
de_string = str(de_string)
crow_args = ["crow", "-s", "de", "-t", "en", "--brief", "-i"]
proc = run(crow_args, stdout=PIPE, input=de_string, encoding="utf-8")
return proc.stdout.rstrip('\n')
# Advances the position of the cursor by one cell down.
def moveDownOne(model, sheet, cell):
# Get the position of the current cell
current_col = cell.CellAddress.Column
current_row = cell.CellAddress.Row
next_col = chr(ord('@') + (current_col + 1))
next_row = current_row + 2
# Get the range of cells in the sheet
cell_range = sheet.getCellRangeByName(f'{next_col}{next_row}')
# Get the cell in the next row
next_cell = cell_range.getCellByPosition(0, 0)
# Set the current selection to the next cell
model.getCurrentController().select(next_cell)
# Translates the text of a cell from German to English then moves down by one cell.
def translateCell():
model = desktop.getCurrentComponent()
# Get the sheet from the model
sheet = model.Sheets.getByIndex(0)
selection = model.getCurrentSelection()
cell = selection.getCellByPosition(0, 0)
de_string = cell.getString()
if de_string != "":
en_string = translateText(de_string)
cell.setString(en_string)
moveDownOne(model, sheet, cell)
If I recall correctly, this script only works if you start libreoffice like this:
soffice --calc --accept="uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"
You also must have the command line utility crow
installed in order to translate text.
Let me know if you encounter any problems.