I'm looking to generate an excel file from styled dataframes. Specifically I want to keep the background colors of cells.
I can generate an excel file with df.to_excel() or df.style.to_excel(), but the background color disappears along the way. Is there any way to keep the background color?
EDIT: The specific code I used:
df = pd.DataFrame([
{ 'color_A_in_red': True , 'A': 1 },
{ 'color_A_in_red': False , 'A': 2 },
{ 'color_A_in_red': True , 'A': 2 },
])
def highlight(x):
c = f"background-color:red"
#condition
m = x["color_A_in_red"]
# DataFrame of styles
df1 = pd.DataFrame('', index=x.index, columns=x.columns)
# set columns by condition
df1.loc[m, 'A'] = c
return df1
df.style.apply(highlight, axis=None)
df.to_excel("test.xlsx")
df.style.apply() does not change df directly but returns a modified copy. The following code works:
df = pd.DataFrame([
{ 'color_A_in_red': True , 'A': 1 },
{ 'color_A_in_red': False , 'A': 2 },
{ 'color_A_in_red': True , 'A': 2 },
])
def highlight(x):
c = f"background-color:red"
#condition
m = x["color_A_in_red"]
# DataFrame of styles
df1 = pd.DataFrame('', index=x.index, columns=x.columns)
# set columns by condition
df1.loc[m, 'A'] = c
return df1
df = df.style.apply(highlight, axis=None)
df.to_excel("test.xlsx")