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 = date.today()
d2 = today.strftime("%B %d, %Y")
writer = pd.ExcelWriter('ExcelExample{}.xlsx'.format(d2), engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
workbook = writer.book
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)
writer.save()
Giving this output
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.
writer.save()
How can I apply the formatting to all sheets either manually or recursively?
