How to highlight rows based on content in Excel Dataframe? How to highlight rows based on content in Excel Dataframe? pandas pandas

How to highlight rows based on content in Excel Dataframe?


You can do it with different excel library, like openpyxl

You can format each cell separatelyFor example:

from openpyxl import Workbookfrom openpyxl.styles import Font, Color, colors, fillsfrom openpyxl.utils.dataframe import dataframe_to_rowswb = Workbook()ws = wb.activefor r in dataframe_to_rows(df, index=False, header=True):    ws.append(r)a1 = ws['A1']a1.font = Font(color="FF0000")a1.fill = fills.PatternFill(patternType='solid', fgColor=Color(rgb='00FF00'))wb.save("pandas_openpyxl.xlsx")

They have great documentation here: https://openpyxl.readthedocs.io/en/stable/pandas.html


If you want to continue using the xlsxwriter Python module you may use the write(…) method on the worksheet object to set the contents and formatting of a cell in one step.

You will have to break up your to_excel() method and write each DataFrame value individually in a loop.

Example cell creation and formatting call:

cell_format = workbook.add_format({'bold': True, 'italic': True})# inside a loop iterating over your DataFrameworksheet.write(row, column, value, cell_format)  # Cell is bold and italic.