I am trying to style dataframes and trying to write the results to an excel sheet. But when I try to write the results to excel, it doesn't preserve the styling. Here is what I have tried.
import pandas as pd
df1 = pd.DataFrame({'Data': ["Hello", "Hai", "Hello", "Hai", "Hello", "Hai", "Hello"],'Data1': [10, 20, 30, 20, 15, 30, 45], })
df2 = pd.DataFrame({'Data': ["Hello", "Hai", "Hello", "Hai", "Hello", "Hai", "Hello"],'Data1': [10, 20, 30, 20, 15, 30, 45], })
data_to_be_colored = "Hello"
df1 = df1.style.apply(lambda x: ['background:lightblue' if x == data_to_be_colored else 'background:lightgrey' for x in df1.Data], axis=0)
df3 = {'Test 1': df1, 'Test 2': df2}
writer = pd.ExcelWriter(r'Styled_Excel.xlsx')
for sheetname, df in df3.items():
df.to_excel(writer, sheet_name=sheetname, index = False)
worksheet = writer.sheets[sheetname]
writer.save()
Receiving Error:
AttributeError: 'Styler' object has no attribute 'style'
Can someone tell me what's wrong with the above code and how to write to excel preserving the styles?