Search code examples
pythonexcelpandasreport

Export styled dataframe to Excel (background color)


I'm looking to generate an excel file from styled dataframes. Specifically I want to keep the background colors of cells.

My styled dataframe

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?

enter image description here

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")

Solution

  • 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")
    

    enter image description here