Skip to main content

Basic Python macros in Libre Office Calc

There are only a few Libre Office Python macro examples in the internet. Here are some basic macros:

Insert the current time in the cell D1:
from datetime import datetime
def insert_time(*args):
 desktop = XSCRIPTCONTEXT.getDesktop()
 model = desktop.getCurrentComponent()
 active_sheet = model.CurrentController.ActiveSheet
 now = datetime.now()
 current_time = now.strftime("%H:%M:%S")
 active_sheet.getCellByPosition(3,0).setFormula(current_time)
 return
Delete contents of the Column A:
def delete_column_contents(*args):
 desktop = XSCRIPTCONTEXT.getDesktop()
 model = desktop.getCurrentComponent()
 active_sheet = model.CurrentController.ActiveSheet
 column = active_sheet.getCellByRangeName("A:A")
 column.clearContents(1) #unfortunately this code deletes numbers only
 return
Place a cursor on the cell A11 (it is more like a workaround, partly derived from this forum):
def gotoCell(*args):
 desktop = XSCRIPTCONTEXT.getDesktop()
 model = desktop.getCurrentComponent()
 active_sheet = model.CurrentController.ActiveSheet
 cell=active_sheet.getCellByPosition(0,10)
 model.CurrentController.select(cell)
 #the code below deselects the "blue" part of the selection
 dummy = model.createInstance("com.sun.star.sheet.SheetCellRanges")
 view = model.getCurrentController()
 view.select(dummy)
 return

Disclaimer: please use the macros of this post at your own risk. The macros are provided 'as is'. There is no guarantee that the macros provided here are the most efficient ones. The author of this post does not bear any responsibility, arising from using the macros provided in this post.

Comments