Search code examples
excelpython-3.xopenpyxlminidom

How to detect if excel has used any filter in openpyxl


I am using openpyxl python library to read excel sheets.

As we know we may have filters in excel. I need to check whether my excel sheet has used any filters using openpyxl.

see this

pic.

I am reading the xml like below.

    import openpyxl
    self.work_book = openpyxl.load_workbook(self.file_name, data_only=True)
    print(self.work_book.sheetnames)  -- > print all sheet name

Any help would be greatly appreciated. Thank you.


Solution

  • I started by reading the documentation about sorting and filtering at openpyxl. After seeing that there was an auto_filter property on the Worksheet object it looks like you can access that property to find the filters

    from openpyxl import load_workbook
    
    work_book = load_workbook('path_to_file')
    work_sheet = work_book.active
    
    if(len(work_sheet.auto_filter.filterColumn) > 0 ):
        print('Hello')
    

    There is also some more detailed documentation about the AutoFilter object too

    Let me know if this helps.