Skip to content

Instantly share code, notes, and snippets.

@rosshiga
Last active September 6, 2022 00:23
Show Gist options
  • Select an option

  • Save rosshiga/8e5c296dc787f1e99f0a4f809d3a3dac to your computer and use it in GitHub Desktop.

Select an option

Save rosshiga/8e5c296dc787f1e99f0a4f809d3a3dac to your computer and use it in GitHub Desktop.
Pretty Pandas to Excel Autofit and AutoFilter
import pandas as pd
import xlsxwriter
def dataframes2xls(dfs,fname, path=''):
with pd.ExcelWriter(path + fname + '.xlsx', engine='xlsxwriter') as writer:
for name,df in dfs.items():
df.to_excel(writer, index=False, header=True, sheet_name=name)
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets[name]
# Get the dimensions of the dataframe.
(max_row, max_col) = df.shape
# Make the columns wider for clarity.
for (col_name,col_data) in df.iteritems():
col_index = df.columns.get_loc(col_name)
max_len = col_data.map(lambda x: len(str(x))).max()
max_len = max(max_len,len(col_name))
worksheet.set_column(col_index,col_index, max_len+6)
# Set the autofilter.
worksheet.autofilter(0, 0, max_row, max_col - 1)
def dataframe2xls(df,name, path=''):
dataframes2xls({name:df},name, path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment