Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to add autofilter to all columns using xlsxwriter without specifying a column range?

I have a dataframe which I am writing to excel using xlsxwriter and I want there to be autofilter applied to all columns where the header is not blank in my spreadsheet without having to specify a range (e.g. A1:D1). Is there any way to do this?

like image 574
Rafid Reaz Avatar asked Apr 03 '20 20:04

Rafid Reaz


People also ask

How do I hide columns in Xlsxwriter?

To hide specific rows or columns in a worksheet, set hidden parameter to 1 in set_row() or set_column() method. The following statement hides the columns C, D and E in the active worksheet.

How do I AutoFit column width in Xlsxwriter?

Is there an “AutoFit” option for columns? Unfortunately, there is no way to specify “AutoFit” for a column in the Excel file format. This feature is only available at runtime from within Excel.


1 Answers

You will need to specify the range in some way but you can do it programatically based on the shape() of the data frame.

For example:

import xlsxwriter
import pandas as pd

df = pd.DataFrame({'A' : [1, 2, 3, 4, 5, 6, 7, 8],
                   'B' : [1, 2, 3, 4, 5, 6, 7, 8],
                   'C' : [1, 2, 3, 4, 5, 6, 7, 8],
                   'D' : [1, 2, 3, 4, 5, 6, 7, 8]})

writer = pd.ExcelWriter('test.xlsx', engine = 'xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter objects from the dataframe writer object.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Apply the autofilter based on the dimensions of the dataframe.
worksheet.autofilter(0, 0, df.shape[0], df.shape[1])

workbook.close()
writer.save()

Output:

enter image description here

like image 198
jmcnamara Avatar answered Sep 21 '22 12:09

jmcnamara