Search code examples
pythonexcelpython-3.xpandasxlrd

How to color text in a cell containing a specific string using pandas


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?


Solution

  • 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.