Skip to content

Instantly share code, notes, and snippets.

@agharbeia
Last active April 19, 2021 22:41
Show Gist options
  • Save agharbeia/a2f1751ba1b0ec6be370174c9390d471 to your computer and use it in GitHub Desktop.
Save agharbeia/a2f1751ba1b0ec6be370174c9390d471 to your computer and use it in GitHub Desktop.
LibreOffice Calc macro in Python to fill empty column cells to value on top
# This is LibreOffice Calc macro to set the values of empty cells in
# a column to the value of the first non-empty cells above the empty range.
# It is meant to be used to normalise table rows after unmerging cells
# in compound tables, thus converting them to simple tables that can then
# be algorithmically processed or exported to tabular formats such as CSV.
#
# Themacro is authored by Ahmad Gharbeia<ahmad@gharbeia.org>
# on 2020-05-19 and is licensed under GPL 3.0 license.
#from __future__ import unicode_literals
from com.sun.star.table.CellContentType import EMPTY, VALUE, TEXT, FORMULA
import uno
def range_head_filler(*args):
desktop = XSCRIPTCONTEXT.getDesktop()
model = desktop.getCurrentComponent()
try:
sheets = model.getSheets()
except AttributeError:
raise Exception("This script is for Calc Spreadsheets only")
sheet = model.CurrentController.getActiveSheet()
oArea = model.getCurrentSelection().getRangeAddress()
first_col = oArea.StartColumn
first_row = oArea.StartRow
last_col = oArea.EndColumn
last_row = oArea.EndRow
col = first_col
while col <= last_col:
row = first_row
token = ""
while row <= last_row:
while sheet.getCellByPosition(col, row).getType() == EMPTY:
if token != "":
sheet.getCellByPosition(col, row).setString(token)
if row == last_row:
break
row += 1
else:
token = sheet.getCellByPosition(col, row).getString()
row += 1
col += 1
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment