1

After running my algorithms I saved all the data in an excel file using pandas.

writer = pd.ExcelWriter('Diff.xlsx', engine='xlsxwriter')

Now, some of the cells contain strings which includes "-->" in it. I have the row and column number for those cells using:

xl_rowcol_to_cell(rows[i],cols[i])

But I couldn't figure how to color those cells or atleast the whole text in it.

Any suggestions/tips?

2 Answers 2

5

You could use a conditional format in Excel like this:

import pandas as pd


# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': ['foo', 'a --> b', 'bar']})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Add a format. Light red fill with dark red text.
format1 = workbook.add_format({'bg_color': '#FFC7CE',
                               'font_color': '#9C0006'})

# Apply a conditional format to the cell range.
worksheet.conditional_format(1, 1, len(df), 1,
                             {'type':     'text',
                              'criteria': 'containing',
                              'value':    '-->',
                              'format':   format1}) 

# Close the Pandas Excel writer and output the Excel file.
writer.save()


Output:

enter image description here

See Adding Conditional Formatting to Dataframe output in the XlsxWriter docs.

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

Comments

0
def highlight (dataframe):

    if  dataframe[dataframe['c'].str.contains("-->")]:

        return ['background-color: yellow']*5
    else:
        return ['background-color: white']*5


df.style.apply(highlight, axis=1)

1 Comment

So,here,the dataframe would be - writer, as per my example? and df will be writer too?

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.