Can xlswriter 'filter_column' be set to sort a column within a filtered range

52 Views Asked by At

Is it possible to sort a column within a .xlsx file using Python's 'xlswriter' module? Here is some sample code:

import xlsxwriter

wb = xlsxwriter.Workbook('test.xlsx')
ws = wb.add_worksheet()

data = (
   ['Region', 'SalesRep', 'Product', 'Units'],
   ['East',   'Tom',      'Apple',    6380],
   ['West',   'Fred',     'Grape',    5619],
   ['North',  'Amy',      'Pear',     4565],
   ['South',  'Sal',      'Banana',   5323],
   ['South',  'Hector',   'Apple',    9814]
)
for row in range(len(data)):
   ws.write_row(row,0, data[row])
   
ws.filter_column(2, <?????>)
1

There are 1 best solutions below

1
Darkmode On

Alternative solution

I speculate you want to apply a filter to a known column of the working workbook. This solution will add the filter but the sorting can only take place at runtime as a feature of the MS Excel.

from openpyxl import load_workbook

original_file = "data.xlsx"

# Open Excel file with openpyxl
# and loading the workbook
wb = load_workbook(original_file)
worksheet = wb.active

# Adjust range based on your data
worksheet.auto_filter.ref = "A1:A6"

# Saving the modified workbook
wb.save("data_with_filter.xlsx")

For your convenience:

pip install openpyxl