I am looking for a way to Efficiently check of a range of cells are empty.
Copilot gave me this. I loops over every cell to see if it empty.
Does anyone know if there is a more efficient way?
My code is going to be part of a plugin so it could be that sometimes I need to check large ranges.
The main purpose is to be sure that cell are empty before applying a formula array to the range.
def is_range_empty(doc, sheet_name, range_address):
"""
Check if a specified range of cells is empty in a LibreOffice Calc sheet.
:param doc: The document object.
:param sheet_name: The name of the sheet to check.
:param range_address: The address of the cell range (e.g., "A1:C3").
:return: True if the range is empty, False otherwise.
"""
# Access the specified sheet by name
sheet = doc.Sheets.getByName(sheet_name)
# Get the cell range
cell_range = sheet.getCellRangeByName(range_address)
# Get the range addresses
start_column = cell_range.RangeAddress.StartColumn
end_column = cell_range.RangeAddress.EndColumn
start_row = cell_range.RangeAddress.StartRow
end_row = cell_range.RangeAddress.EndRow
# Iterate over each cell in the range
for row in range(start_row, end_row + 1):
for col in range(start_column, end_column + 1):
cell = sheet.getCellByPosition(col, row)
# Check if the cell is empty
if cell.Type != 0: # 0 corresponds to EMPTY cell type
return False
return True
# Example usage
def check_empty_cells():
# Access the current document
doc = XSCRIPTCONTEXT.getDocument()
# Specify the sheet name and cell range
sheet_name = "Sheet1"
range_address = "A1:C3"
# Check if the range is empty
if is_range_empty(doc, sheet_name, range_address):
print("The range is empty.")
else:
print("The range is not empty.")