Skip to content Skip to sidebar Skip to footer

How To Autofilter Excel-sheet Before Outputting

I am making function for a script that fetches data from an api which will output a dataframe to an excel-sheet. I need autofiltering(as an optional argument). I am almost done,

Solution 1:

Thanks for the input. I solved the problem using pandas and xlsxwriter engine, in a writer object:

if auto_filter == True:
        for worksheet in writer.sheets.values():
            row_count = len(df.index)
            column_count = len(df.columns)
            worksheet.autofilter(0, 0, row_count-1, column_count-1)                                
    writer.save()
    print("Excel-file generated.")

Solution 2:

I think you first need to add the auto filter, assuming you're using OpenPyXl:

To add a filter you define a range and then add columns and sort conditions

ws.auto_filter.ref = "A1:B15"
ws.auto_filter.add_filter_column(0, ["Kiwi", "Apple", "Mango"])
ws.auto_filter.add_sort_condition("B2:B15") ```

Of course you can omit the add_filter and add_sort_conditions, and leave that to the user to configure. You will need to do simply:

worksheet.auto_filter.ref = worksheet.dimensions

Post a Comment for "How To Autofilter Excel-sheet Before Outputting"