4

I am using the below code to export my df to excel, I have a requirement to color the particular columns in the output excel.

# DF TO EXCEL
from pandas import ExcelWriter
writer = ExcelWriter('Output.xlsx')
df.to_excel(writer,'sheet1')
writer.save()

Please suggest me an approach.

4
  • Is this even possible??? Commented Feb 23, 2017 at 6:12
  • Color how? Like the text color? Commented Feb 23, 2017 at 6:25
  • 1
    @DYZ It is possible but not sure how to implement on DF - Please check stackoverflow.com/questions/7746837/… Commented Feb 23, 2017 at 6:32
  • @Nick T - Column wise background coloring Commented Feb 23, 2017 at 6:34

2 Answers 2

8

You can use:

import string
np.random.seed(100)
df = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('GHIJK'))
print (df)
   G  H  I  J  K
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

If need set all selected columns to same color:

writer = pd.ExcelWriter('file1.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')

#set format
workbook = writer.book
format = workbook.add_format({'bg_color': 'red'})
worksheet = writer.sheets['Sheet1']

#dict for map excel header, first A is index, so omit it
d = dict(zip(range(25), list(string.ascii_uppercase)[1:]))
print (d)
{0: 'B', 1: 'C', 2: 'D', 3: 'E', 4: 'F', 5: 'G', 6: 'H', 7: 'I', 8: 'J',
 9: 'K', 10: 'L', 11: 'M', 12: 'N', 13: 'O', 14: 'P', 15: 'Q', 16: 'R', 
 17: 'S', 18: 'T', 19: 'U', 20: 'V', 21: 'W', 22: 'X', 23: 'Y', 24: 'Z'}

 #select columns of df
cols = ['G','J','K']

#in loop set background color where are data
#http://xlsxwriter.readthedocs.io/working_with_conditional_formats.html
for col in cols:
    excel_header = str(d[df.columns.get_loc(col)])
    len_df = str(len(df.index) + 1)

    rng = excel_header + '2:' + excel_header + len_df
    worksheet.conditional_format(rng, {'type': 'no_blanks',
                                       'format': format})
writer.save()

excel1

If need set all selected columns to different color:

writer = pd.ExcelWriter('file1.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')

#set format
workbook = writer.book
worksheet = writer.sheets['Sheet1']

#dict for map excel header, first A is index, so omit it
d = dict(zip(range(25), list(string.ascii_uppercase)[1:]))
print (d)
{0: 'B', 1: 'C', 2: 'D', 3: 'E', 4: 'F', 5: 'G', 6: 'H', 7: 'I', 8: 'J',
 9: 'K', 10: 'L', 11: 'M', 12: 'N', 13: 'O', 14: 'P', 15: 'Q', 16: 'R', 
 17: 'S', 18: 'T', 19: 'U', 20: 'V', 21: 'W', 22: 'X', 23: 'Y', 24: 'Z'}

 #select columns of df
cols = ['G','J','K']
colors = ['red','yellow','blue']

#in loop set background color where are data
#http://xlsxwriter.readthedocs.io/working_with_conditional_formats.html
for i, col in enumerate(cols):
    format = workbook.add_format({'bg_color': colors[i]})
    excel_header = str(d[df.columns.get_loc(col)])
    len_df = str(len(df.index) + 1)

    rng = excel_header + '2:' + excel_header + len_df
    worksheet.conditional_format(rng, {'type': 'no_blanks',
                                       'format': format})
writer.save()

excel2

Sign up to request clarification or add additional context in comments.

3 Comments

I have amended your script with my dataframe , getting an error "KeyError: 'I'". Any clue pls?
sorry that's my mistake, I gave an invalid column name.Its working fine. Thanks a lot! :)
@jezrael is it possible to color individual cell depends on its value?
3

A little update for those that would find this question; today Pandas is including style functions and styler objects, and this is extremely practical to achieve what you want without going through very convoluted methods. https://pandas.pydata.org/pandas-docs/stable/style.html

Comments

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.