0

Consider this dummy DataFrame below:

df = pd.DataFrame(np.random.rand(15).reshape(5,3), columns='x y z'.split())

# df
          x         y         z
0  0.725005  0.318429  0.918186
1  0.883890  0.993736  0.795322
2  0.687472  0.328307  0.108520
3  0.608381  0.193478  0.469421
4  0.598708  0.276778  0.433235

Assume the below simple pandas styling applied:

style = df.style \
    .set_table_styles([{'selector': 'th', 'props': [('background-color', 'orange')]}]) \
    .applymap(lambda x: 'color: red' if x >.5 else 'color: blue')

The style.render() seem to confirm the styling has applied for th and td (snippet below):

<style  type="text/css" >
    #T_8b7f1124_a115_11ea_8cf8_48452026764f th {
          background-color: orange;
    }    #T_8b7f1124_a115_11ea_8cf8_48452026764frow0_col0 {
            color:  red;
        }    #T_8b7f1124_a115_11ea_8cf8_48452026764frow0_col1 {
            color:  blue;
        } ...

Exporting this as an html displays all the colours as expected. However when I apply to_excel, only the elemental styling is picked up. The headers/index remains default colours:

style.to_excel(r'somefile.xlsx')

I tried both xlsxwriter and openpyxl as engine, both exhibit the same behaviour.

I searched a few questions on set_table_styles and Styler.to_excel, but all seem to be concerned about the individual elements, didn't seem to address the combination thereof. Tried searching issue log on github as well, haven't ran into a match so far.

Anybody had luck getting set_table_styles and Styler.to_excel to work together?

r.ook
  • 13,466
  • 2
  • 22
  • 39

1 Answers1

0

This seems to be a bug that still exists in the current version (1.0.3). I have raised a bug in their repo: https://github.com/pandas-dev/pandas/issues/34438

Will try to update this when it gets resolved...

r.ook
  • 13,466
  • 2
  • 22
  • 39