1

I have applied the following conditional formatting to a dataframe. Now, however, I want to export the dataframe to an Excel file without losing the colour formatting. Any ideas?

def highlight(ex):
    if ex.Monatsgehalt_September == 0 or ex.Bonus == 0:
        return ['color: red']*col
    else:
        return ['color: black']*col

ex.style.apply(highlight, axis=1)

2 Answers 2

2

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')
Sign up to request clarification or add additional context in comments.

Comments

1

you can't export pandas conditional formatting but you can use the module xlsxwriter

https://xlsxwriter.readthedocs.io/example_conditional_format.html#ex-cond-format

3 Comments

I have not been able to read an Excel file with XlsxWriter and then apply formatting and export. Do you have any suggestions as to how to do this? Highly appreciated!
Save you excel file with pandas. Then open it with XlsxWriter and use it to format your table. (That's the way I use it) You have to install java to make it work.
@SkanderHR Xlsxwriter is a pure python package and doesn't require any Java installation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.