Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting and auto filtering Excel with openpyxl

I am trying to sort a spreadsheet using openpyxl and Python. I have read the documents and I don't quite understand this page. I am expecting it to either add the auto filter dropdown arrows or sort my spreadsheet and it is returning errors. Here's my code

wb = openpyxl.load_workbook('report.xlsx')
ws = wb.active
ws['A2'] = "Store"
ws['B2'] = "Manager"
ws['C2'] = "Zone"
ws.column_dimensions.group('F','DU',hidden=True)
#ws.AutoFilter.add_sort_condition('C:C')
wb.save("report.xlsx")

According to the documents it looks like the line "ws.AutoFilter.add_sort_condition('C:C')" should give me the result I want. (Yes I understand it is currently a comment line. The rest of my code runs fine without that line so I commented it.)

When I have that line in the code I get the error - 'Worksheet' object has no attribute 'AutoFilter' but according to the documents it looks like it does. http://openpyxl.readthedocs.org/en/latest/_modules/openpyxl/worksheet/filters.html#AutoFilter.

If anyone can help explain to me why it is failing or what the documents mean that would be great.

This statement in the documents is particularly confusing to me:

"Don't create auto filters by yourself. It is created by :class:~openpyxl.worksheet.Worksheet. You can use via :attr:~~openpyxl.worksheet.Worksheet.auto_filter attribute."

because I tried that too and it also failed.

Update: @crussell's reply worked in that it added the auto filter to my spreadsheet. However, it is still not adding the sort condition to the appropriate column.

like image 734
Nick Reinhart Avatar asked Sep 16 '15 17:09

Nick Reinhart


2 Answers

See here: http://openpyxl.readthedocs.org/en/latest/api/openpyxl.worksheet.html?highlight=auto_filter#openpyxl.worksheet.worksheet.Worksheet.auto_filter

The auto_filter command returns the AutoFilter object, so in a sense they are the same thing.

What you need is ws.auto_filter.ref = 'C1:C20' with the range of cells those of which you want to filter.

like image 111
crussell Avatar answered Sep 19 '22 11:09

crussell


According to the documentation openpyxl can define the filter and/or sort but does not apply them!

They can only be applied from within Excel

like image 23
Jaime Espinosa Camino Avatar answered Sep 20 '22 11:09

Jaime Espinosa Camino