简体   繁体   English

在 XlsxWriter 中使用带有条件格式的 for 循环的问题

[英]Issues with using a for loop with conditional formatting in XlsxWriter

Python 2.7: Python 2.7:

I am trying to bold all the cells that contain a certain text in excel using XlsxWriter.我正在尝试使用 XlsxWriter 将 excel 中包含特定文本的所有单元格加粗。 I have stored the text in a list and used a for loop to iterate over the elements.我已将文本存储在列表中,并使用 for 循环遍历元素。 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.我不确定我是否使用正确的语法来指定 XlsXwriter 提供的conditional_format字典中的“值”键的值。 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})


You need to use the header strings as the values in conditional format, and they need to be double quoted (as required by Excel).您需要使用 header 字符串作为条件格式的值,并且它们需要双引号(根据 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: Output 目标词以粗体显示:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM