Search code examples
python-3.xpandasexceldataframexlsxwriter

Highlighting excel cells based on the cell values using pandas dataframe and xlsxwriter


I have a csv file. After doing certain process, it has to be saved as an excel file.

I am opening it as pandas dataframe and after doing some cleaning (renaming and rearranging columns, dropping few columns), i have to replace null values or if the cell value is "N/A" to "DN". Currently i am using two lines of code for this.

df.replace('', np.nan, inplace = True)
df.replace('N/A', np.nan, inplace = True)
df = df.fillna("DN")

Then, i have to highlight cells which has the value "DN" with yellow color

I am trying with the code mentioned in this post How Do I Highlight Rows Of Data? Python Pandas issue. But in the output excel nothing is getting highlighted. Below is the code i am currently working with

df.replace('', np.nan, inplace = True)
df.replace('N/A', np.nan, inplace = True)
df = df.fillna("NA")
df.index = np.arange(1, len(df) + 1)

def high_color(val):
    color = 'yellow' if val == 'NA' else ''
    return 'color: {}'.format(color)
result = df.style.applymap(high_color)

writer_orig = pd.ExcelWriter(out_name, engine='xlsxwriter')
df.to_excel(writer_orig, sheet_name='report', index=True, index_label="S_No", freeze_panes=(1,1))

workbook  = writer_orig.book
worksheet = writer_orig.sheets['report']
# Add a header format.
header_format = workbook.add_format({
    'bold': True,
    'fg_color': '#ffcccc',
    'border': 1})
    
for col_num, value in enumerate(df.columns.values):
    worksheet.write(0, col_num + 1, value, header_format)
writer_orig.close()

Any kind of suggestions will be greatly helpful.


Solution

  • You have to export to excel with result Styler:

    # Demo
    def high_color(val):
        return 'background-color: yellow' if val == 'NA' else None
    
    result = df.style.applymap(high_color)
    result.to_excel('styler1.xlsx')
    df.to_excel('styler2.xlsx')
    

    Export from result

    enter image description here

    Export from df

    enter image description here