Applying formatting to multiple Excel sheets using Python and XLSXWriter

I have two dataframes as follows:

import pandas as pd 
import numpy as np
from datetime import date

df = pd.DataFrame({'Data': [10, 22, 31, 43, 57, 99, 65, 74, 88],
                  'Data2':[10, 22, 31, 43, 57, 99, 65, 74, 88],
                  'Data3':[10, 22, 31, 43, 57, 99, 65, 74, 88]})

df2 = pd.DataFrame({'df2_Data': ['blue', 'yellow', 'purple', 'orange', 'green', 'brown', 'gray', 'white', 'red'],
                  'df2_Data2':['bike', 'car', 'bus', 'train', 'boat', 'truck', 'plane', 'scooter', 'skateboard'],
                  'df2_Data3':['chicken', 'cow', 'dog', 'crocodile', 'snake', 'pig', 'rat', 'mouse', 'monkey']})

I can export df, with the desired formatting, as a single sheet in an Excel with the following code:

today =
d2 = today.strftime("%B %d, %Y")

writer = pd.ExcelWriter('ExcelExample{}.xlsx'.format(d2), engine='xlsxwriter')

df.to_excel(writer, sheet_name='Sheet1')
workbook  =
worksheet = writer.sheets['Sheet1']

header_format = workbook.add_format({
    'bold': True,
    'text_wrap': True,
    'valign': 'top',
    'fg_color': '#38C4F1',
    'font_color': 'FFFFFF',
    'border': 1})

for col_num, value in enumerate(df.columns.values):
    worksheet.write(0, col_num + 1, value, header_format)

Giving this output

enter image description here

OR, I can export both dataframes as separate sheets withno formatting using this code:

writer = pd.ExcelWriter(‘ExcelExample{}.xlsx’.format(d2), engine=’xlsxwriter’)

# Write each dataframe to a different worksheet.
df.to_excel(writer, sheet_name='Sheet1')
df2.to_excel(writer, sheet_name='Sheet2')

# Close the Pandas Excel writer and output the Excel file.

How can I apply the formatting to all sheets either manually or recursively?


The below code from this [post][1] allows me to achieve my aim of applying formatting to multiple sheets:

writer = pd.ExcelWriter('ExcelExample{}.xlsx'.format(d2), engine='xlsxwriter')

data_frame_for_writer=[df, df2]

for i,j in zip(data_frame_for_writer,sheets_in_writer):
#(max_row, max_col) = df.shape
#column_settings = [{'header': column} for column in df.columns]

### Assign WorkBook
# Add a header format
header_format = workbook.add_format({'bold': True,'text_wrap': True,'size':10,
                                                      'valign': 'top','fg_color': '#c7e7ff','border': 1})

### Apply same format on each sheet being saved
for i,j in zip(data_frame_for_writer,sheets_in_writer):
    for col_num, value in enumerate(i.columns.values):
        writer.sheets[j].set_column(0, max_col - 1, 12)
#       writer.sheets[j].add_table(0, 0, max_row, max_col - 1, {'columns': column_settings,'autofilter': True})
        writer.sheets[j].write(0, col_num, value, header_format)


Leave a Reply

Your email address will not be published. Required fields are marked *