python - 使用 Python 的 xlsxwriter 在 Excel 中的字符串条件格式 "equal to"

标签 python excel string-matching conditional-formatting xlsxwriter

我有相对较大的 Excel 电子表格,我在其中应用条件格式。但是,单元格的内容相对较短(最多 3 个字母)。所以,我需要精确匹配一个字符串。 例如:“A”应该被格式化,但仅包含“A”(“ABC”、“BCA”、“BAC”等)。

我尝试了使用“文本”和“单元格”选项的不同选项,但我惨遭失败。这是我的测试用例:

import xlsxwriter

workbook = xlsxwriter.Workbook('conditional_format4.xlsx')
worksheet1 = workbook.add_worksheet()

format1 = workbook.add_format({'bg_color': '#FFC7CE',
                               'font_color': '#9C0006'})

data = [
    ['ABC', 'BCA', 38, 30, 75, 48, 75, 66, 84, 86],
    [6, 24, 1, 84, 54, 62, 60, 3, 26, 59],
    [28, 79, 97, 13, 85, 93, 93, 22, 5, 14],
    [27, 'BAC', 40, 17, 18, 79, 90, 93, 29, 47],
    [88, 'ABC', 33, 23, 67, 1, 59, 79, 47, 36],
    [24, 'A', 20, 88, 29, 33, 38, 54, 54, 88],
    [6, 'BCA', 88, 28, 10, 26, 37, 7, 41, 48],
    [52, 78, 1, 96, 26, 45, 47, 33, 96, 36],
    [60, 54, 81, 66, 81, 90, 80, 93, 12, 55],
    [70, 5, 46, 14, 71, 19, 66, 36, 41, 21],
]

for row, row_data in enumerate(data):
    worksheet1.write_row(row, 0, row_data)


worksheet1.conditional_format('A1:J10', {'type': 'text',
                                         'criteria': 'containing',
                                         'value': 'A',
                                         'format': format1})

workbook.close()

所以,我只想匹配一个单元格。我的选择/想法用完了。这看起来微不足道,但我收到很多错误,表明我的 Excel 文件不正确。希望有人找到解决这个问题的方法。

这是在 Excel 2010 中完成的(条件格式 -> 突出显示单元格规则 -> 等于:在文本框中键入 A)。

最佳答案

以下 XlsxWriter 条件格式应该有效:

worksheet1.conditional_format('A1:J10', {'type': 'cell',
                                         'criteria': '==',
                                         'value': '"A"',
                                         'format': format1})

请注意,与在 Excel 中一样,条件类型应为 cell,值应为字符串(带引号)。

关于python - 使用 Python 的 xlsxwriter 在 Excel 中的字符串条件格式 "equal to",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32066961/

相关文章:

vba - word vba不会关闭excel应用程序

VBA(Excel): Looped copy on multiple criteria in multiple worksheets

c - 是否可以允许 KMP 算法不匹配?

ruby - ruby 混淆中的正则表达式匹配

Python:使用 ElementTree 访问 XML 中的下一个元素

python - 过滤元组列表以删除所有奇数或总和小于 80 的列表

Excel RANDBETWEEN 作为字符串

python - 使用 scipy 计算卷积时出现 ValueError

python - 曼哈顿度量中的 Voronoi 图

regex - 匹配算法还是正则表达式?