MomentoMori4
MomentoMori4

Reputation: 63

Issues with using a for loop with conditional formatting in XlsxWriter

Python 2.7:

I am trying to bold all the cells that contain a certain text in excel using XlsxWriter. I have stored the text in a list and used a for loop to iterate over the elements. I am not sure if I am using the correct syntax for specifying the value of the 'value' key in the conditional_format dictionary that XlsXwriter offers. The cells that contain the strings in my dictionary are not being converted into bold format.

header_format = new_wb.add_format({'bold': True})

header_list = ["Issue", "Type", "Status", "Resolution", "Summary", "Priority", "Fix Version", "Labels"]

for i in range(len(header_list)):
    new_ws.conditional_format('A1:Z999', {'type': 'cell', 'criteria': 'equal to', 'value': '"header_list[i]"' , 'format': header_format})


Upvotes: 1

Views: 425

Answers (1)

jmcnamara
jmcnamara

Reputation: 41574

You need to use the header strings as the values in conditional format, and they need to be double quoted (as required by Excel). You are trying to do that but your syntax is wrong. Here is a corrected version based on your example:

import xlsxwriter

new_wb = xlsxwriter.Workbook('test.xlsx')
new_ws = new_wb.add_worksheet()

header_format = new_wb.add_format({'bold': True})

header_list = ["Issue", "Type", "Status", "Resolution",
               "Summary", "Priority", "Fix Version", "Labels"]

for value in header_list:
    new_ws.conditional_format('A1:Z999', {'type': 'cell',
                                          'criteria': 'equal to',
                                          'value': '"%s"' % value,
                                          'format': header_format})

# Write some strings to test against.
new_ws.write_column('A1', ['Foo', 'Type', 'Bar', 'Status'])

new_wb.close()

Output with the target words in bold:

enter image description here

Upvotes: 1

Related Questions