How to add column filters to Excel worksheet using XLWINGS?

Viewed 555

I have almost finished my Python script for creating an Excel sheet. One of the last missing points is to add a filtering possibility to the top row of the sheet (CTRL+SHIFT+L shortcut in Excel), no filtering should be made, just added the filter. I know I can open the file and do it myself, but for the sake of automation it would be nice.

Is that possible?

1 Answers

The shortest solution is to call the api property to activate the autofilter:

import xlwings as xw

path = r"test.xlsx"

wb = xw.Book(path)
ws = wb.sheets[0]

ws.used_range.api.AutoFilter(Field:=1)

But you can also use native xlwings functions (create a table object and then set its show_autofilter to True):

import xlwings as xw

path = r"test.xlsx"

wb = xw.Book(path)
ws = wb.sheets[0]

ws.tables.add(ws.used_range, name="a_table")
ws.tables["a_table"].show_autofilter = True
# This way adds formatting in addition to the filter.
Related