This section of the pandas documentation explains how dataframes can be exported to excel with conditional formatting.
Here's a simple example:
import pandas as pd
import numpy as np
# Initialize example dataframe
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))], axis=1)
df.iloc[0, 2] = np.nan
def highlight_max(s):
"""Styling function: highlights the maximum in a Series yellow."""
is_max = s == s.max()
return ['background-color: yellow' if v else '' for v in is_max]
def color_negative_red(val):
"""Styling function: apply red font color to negative values."""
color = 'red' if val < 0 else 'black'
return f'color: {color}'
# Apply conditional formatting to dataframe
styled = df.style.applymap(color_negative_red).apply(highlight_max)
# Export styled dataframe to excel
styled.to_excel('styled.xlsx', engine='xlsxwriter')