Shanoo
Shanoo

Reputation: 1255

make characters bold based on conditionals using xlsxwriter

I have a pandas dataframe that looks as shown in the screenshot. I want to apply conditional formatting using xlsxwriter to make the values of column "C" bold if column "B" value is "Total". The below code doesnot seem to work

bold = workbook.add_format({'bold': True})
l = ['C3:C500']
for columns in l:
    worksheet.conditional_format(columns, {'type': 'text',
                                          'criteria': 'containing',
                                           'value':     'Total',
                                           'font_color': "gray"})

enter image description here

Here is my updated code:

l = ['C3:C500']
for columns in l:
    worksheet.conditional_format(columns, {'type': 'formula',
                                           'criteria': '=$B3="Total"',
                                           'format': bold})
    worksheet.conditional_format(columns, {'type': 'formula',
                                           'criteria': '=$B3!="Total"',
                                           'font_color': "gray"})

Upvotes: 1

Views: 2514

Answers (1)

jmcnamara
jmcnamara

Reputation: 41554

The key to using conditional formats in XlsxWriter is to figure out what you want to do in Excel first.

In this case if you want to format a cell based on the value in another cell you need to use the "formula" conditional format type. You also need to make sure that you get the range and absolute values (the ones with $ signs) correct.

Here is a working example based on your code:

import xlsxwriter

workbook = xlsxwriter.Workbook('conditional_format.xlsx')
worksheet = workbook.add_worksheet()

worksheet.write('B3', 'Total')
worksheet.write('B4', 'Foo')
worksheet.write('B5', 'Bar')
worksheet.write('B6', 'Total')

worksheet.write('C3', 'Yes')
worksheet.write('C4', 'Yes')
worksheet.write('C5', 'Yes')
worksheet.write('C6', 'Yes')

bold = workbook.add_format({'bold': True})
l = ['C3:C500']
for columns in l:
    worksheet.conditional_format(columns, {'type': 'formula',
                                           'criteria': '=$B3="Total"',
                                           'format': bold})

workbook.close()

Output:

enter image description here

Upvotes: 2

Related Questions