2

I want to highlight a cell using python with this code.

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

Num_cols = len (df10.TIME1)
print(Num_cols)
for k in range(0, Num_cols):
    a=0
    if df10["TIME1"][k]!=df10["TIME2"][k]:
        b=str(k)
        a='E'+b
        print(a)
        print(df10["TIME1"][k],df10["TIME2"][k])
        writer = pd.ExcelWriter('4.xlsx', engine='xlsxwriter')
        df10.to_excel(writer, sheet_name='Sheet1')
        workbook  = writer.book
        worksheet = writer.sheets['Sheet1']
        worksheet.conditional_format(a, {'type': '2_color_scale'})
        writer.save()

But it didn't work with this code.If i use this line

worksheet.conditional_format('E3', {'type': '2_color_scale'})

instead of this line.E3 is highlighted.

worksheet.conditional_format(a, {'type': '2_color_scale'}) 

My cell number is variable. I tried also defining "a" value like this a="'"+a+"'" but i get error like that AttributeError: 'NoneType' object has no attribute 'group'

Thanks for your answer.

1

2 Answers 2

2

The conditional_format() method takes a range as input. If you want to apply it to a single cell then duplicate the cell into a range like this:

conditional_format('E3:E3', options)

However, a better approach is to use a numeric range like this:

conditional_format(2, 4, 2, 4, options)

See the docs on conditional_format() and Working with Conditional Formatting.

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

Comments

0

I modified your code slightly and it seems to work now:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint (0,9,(5,5)))

writer = pd.ExcelWriter('4.xlsx', engine='xlsxwriter')
workbook  = writer.book
df.to_excel(writer, sheet_name='Sheet1')
worksheet = writer.sheets['Sheet1'] # select sheet here

Num_cols = 5
print(Num_cols)
for k in range(0, Num_cols):
    a=0
    if df[0][k]!=df[1][k]:
        b=str(k+2) # added shift for header
        a='E'+b
        print(a)
        print(df[0][k],df[1][k])
        worksheet.conditional_format(a, {'type': '2_color_scale'})
writer.save()

AttributeError may come up if address uses lowercase or as some other format problems.

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.