I tried to create an excel file from Python pandas dataframe with the auto filter to display invalid data as default.
Here's my input dataframe df:
ITEM RESULT
A1 VALID
A2 VALID
A# INVALID
I want to add a worksheet 'filter test' on an existing excel file 'filter_output.xlsx' and with auto-filter set to column 'RESULT' to display only 'INVALID' data by default.
Here's my code:
import pandas as pd
from openpyxl import load_workbook
workbook=load_workbook('filter_output.xlsx')
writer = pd.ExcelWriter('filter_output.xlsx', engine='openpyxl')
writer.book=workbook
df.to_excel(writer, 'filter test', index=False)
ws=writer.sheets['filter test']
ws.auto_filter.ref='A:B'
ws.auto_filter.add_filter_column(1, 'INVALID', blank=False)
writer.save()
workbook.close()
I got the following error:
ws.auto_filter.add_filter_column(1, 'INVALID', blank=False)
File "C:\Python27\lib\site-packages\openpyxl\worksheet\filters.py", line 357, in add_filter_column
self.filterColumn.append(FilterColumn(colId=col_id, vals=vals, blank=blank))
File "C:\Python27\lib\site-packages\openpyxl\worksheet\filters.py", line 315, in __init__
self.filters.filter = vals
File "C:\Python27\lib\site-packages\openpyxl\descriptors\sequence.py", line 26, in __set__
raise TypeError("Value must be a sequence")
TypeError: Value must be a sequence
Any idea about how to fix this error ? Is there a better way to create excel with auto filter on to show default value only from pandas dataframe?