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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With