python-3.xpandaspandas-styles

How to change the color of the first row in Excel with Pandas


I have a code where I am writing a xlsx file :

...
...
df.to_excel(finalname,index=False,header=False)

Example:

enter image description here

I would like to write the excel file with color, but just in the first row, like the follow image:

enter image description here

Maybe I can use the df.style.apply,

I tryed that:

result.style.apply('background-color: gray',row=[1], axis=1)

But it isn´t working

style.apply is the correct way ?

If not, how can I get the result of the second image?


Solution

  • You can checkout the python package xlwings

    Here's how I set an excel range's color:

    import xlwings as xw
    df.to_excel(finalname,index=False,header=False)
    wb = xw.Book(finalname)
    
    # color is set with an rgb value 
    wb.sheets['yoursheet'].range('A').color = (169,169,169)
    

    I've not adjusted the text color before but I'm pretty sure it's possible. xlwings is built on top of pywin32

    According to the docs you may be able to get away with setting something like this:

    wb.sheets['sheet1'].range('A').api.Font.ColorIndex = 3