pythonpandasdataframeopenpyxlstyleframe

How to color only sepcific headers in a dataframe and save it to excel


Let say I have dataframe like this:

     col1    sub col 2     col3       col4
0    A        A_1          pass        2
1    A        A_2          pass        4
2    A        A_1          fail        4
3    A        A_1          fail        5
4    A        A_1          pass        3
5    A        A_2          fail        2

I want to change the color of the header "sub col 2" to yellow, then save it as an excel file and have an output excel file like this one when I open the file?

Output


Solution

  • (Assuming you are using styleframe since the question is tagged with )

    You can use the apply_headers_style method with the cols_to_style argument:

    from styleframe import StyleFrame, Styler
    
    ...
    sf.apply_headers_style(Styler(bg_color='yellow'),
                           cols_to_style='sub col 2')
    sf.to_excel('output.xlsx').save()
    

    enter image description here

    If you want the filters as well you can pass row_to_add_filters=0 to to_excel:

    sf.to_excel('output.xlsx', row_to_add_filters=0).save()
    

    enter image description here