2

I am quite new to the Pandas styling and trying to style my Pandas DataFrame and colour the headers grey colour, here is my attempt:

with open ('test.html','w') as test:
    test, df.style.set_properties(**{'text-align': 'center'}).set_table_styles([ dict(selector='th', props=[('text-align', 'center')] ) ]).render()

There are 2 problems and 1 question:

Problems

1 - To colour the headers grey like the excel

2 - exporting as HTML

Question: Is it possible to render the finished styled as an excel file as well?

2
  • Do you want to export as HTML or excel ? Commented May 5, 2020 at 15:52
  • HTML first, then if it's possible to export excel as well. Commented May 5, 2020 at 15:56

1 Answer 1

2

Yes, you can do:

def hover(hover_color="#ffff99"):
    return dict(selector="tr:hover",
                props=[("background-color", "%s" % hover_color)])
styles = [
    hover(),
    dict(selector='thead', props=[('background-color','grey')]),
]

# this forces grey background on header
styler = df.style.set_table_styles(styles)

# HTML string
html = styler.render()

# save html
with open('file.html', 'w') as f:
    f.write(html)

# excel
styler.to_excel('file.xlsx')
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, the excel headers is not colored. And I did not see the HTML file generated. I want to have the HTML file?
@Pythonista you are correct, excel file stills doesn't have gray header. See update for html saving.

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.