Python Openpyxl Filter and Sort Data
Python provides the Openpyxl module, which is used to deal with Excel files without involving third-party Microsoft application software. By using this module, we can have control over excel without open the application. It is used to perform excel tasks such as read data from excel file, or write data to the excel file, draw some charts, accessing excel sheet, renaming sheet, modification (adding and deleting) in excel sheet, formatting, styling in the sheet, and any other task. Openpyxl is very efficient to perform these tasks for you.
The auto_filter attribute is used to set filtering and sorting conditions.
auto_filter Return AutoFilter object. auto_filter attribute stores/returns string until 1.8. You should change your code like ws.auto_filter.ref = "A1:A3". Changed in version 1.9
Consider the following code:
from openpyxl import Workbook
wb = Workbook()
sheet = wb.active
sheet['A3'] = 40
sheet['B3'] = 26
row_count = [
(93,45),
(23,54),
(80,43),
(21,12),
(63,29),
(34,15),
(80,68),
(20,41)
]
for row in row_count:
sheet.append(row)
print(sheet.dimensions)
for a1,a2 in sheet[sheet.dimensions]:
print(a1.value, a2.value)
sheet.auto_filter.add_sort_condition('B2:B8')
sheet.auto_filter.add_filter_column(1, ['40', '26'])
wb.save('dimension_1.xlsx')
Output:
A3:B11
40 26
93 45
23 54
80 43
21 12
63 29
34 15
80 68
20 41
Comments
Angelo
2-May-2021 08:52:17 AM