The same vba macro above created by @sokol92 , converted to python. It really filtered different types at the same time, although in the graphical interface it only shows the background color radiobutton is selected.
Thanks a lot for the help
import uno
from com.sun.star.sheet import TableFilterField3, FilterFieldValue
from com.sun.star.sheet.FilterFieldType import BACKGROUND_COLOR, TEXT_COLOR, STRING
from com.sun.star.sheet.FilterOperator import EQUAL
def rgb_to_long(rgb):
"""Convert an RGB color tuple to libreoffice long integer format
Args:
rgb (tuple): (255,0,0)
Returns:
int: LO long int
"""
r = rgb[0] * 256 * 256
g = rgb[1] * 256
b = rgb[2]
return r+g+b
def str_hex_to_long(str_hex):
"""Converts a hexadecimal color string to libreoffice long integer format
Args:
str_hex (str): 'ff0000' or '#ff0000'
Returns:
int: LO long int
"""
return int(str_hex.replace('#', ''), 16)
def apply_filter(*args):
REF_CELL = 'A1'
doc = XSCRIPTCONTEXT.getDocument()
sheets = doc.Sheets
my_sheet = sheets[0]
cell = my_sheet[REF_CELL]
range = get_range(cell)
filter_by(range, 0)
def get_range(ref_cell):
sheet = ref_cell.Spreadsheet
cursor = sheet.createCursorByRange(ref_cell)
cursor.collapseToCurrentRegion()
return cursor
def filter_by(range, ref_field):
NAME = 'data_tmp'
doc = XSCRIPTCONTEXT.getDocument()
db_ranges = doc.DatabaseRanges
if db_ranges.hasByName(NAME):
db_ranges.removeByName(NAME)
db_ranges.addNewByName(NAME, range.RangeAddress)
data = db_ranges.getByName(NAME)
data.AutoFilter = True
#ffvalue = [FilterFieldValue() for _ in range(3)] #<class 'TypeError'>: 'pyuno' object is not callable
ffvalue0 = FilterFieldValue()
ffvalue1 = FilterFieldValue()
ffvalue2 = FilterFieldValue()
ffvalue0.FilterType = BACKGROUND_COLOR
#ffvalue0.ColorValue = rgb_to_long((255,0,0))
ffvalue0.ColorValue = str_hex_to_long('ff0000')
#ffvalue0.ColorValue = -1 #No fill
ffvalue1.FilterType = TEXT_COLOR
#ffvalue1.ColorValue = rgb_to_long((255,0,0))
ffvalue1.ColorValue = str_hex_to_long('ff0000')
#ffvalue1.ColorValue = -1 #Automatic
ffvalue2.FilterType = STRING
ffvalue2.StringValue = 'red'
ff = TableFilterField3()
ff.Field = ref_field
ff.Operator = EQUAL
#ff.Values = (ffvalue0,)
ff.Values = (ffvalue0, ffvalue1, ffvalue2)
fd = data.getFilterDescriptor()
fd.ContainsHeader = True
fd.FilterFields3 = ((ff,))
data.refresh()
Note1: is there any native way to convert tuple rgb to libreoffice long int in Python macros? I made two custom functions for this.
Note2: I tried to generate the FilterFieldValue objects by loop, but it displays the error message:
ffvalue = [FilterFieldValue() for _ in range(3)]
<class ‘TypeError’>: ‘pyuno’ object is not callable