使用xlsxwriter根据条件使字符变粗

问题描述 投票:1回答:1

我有一个pandas数据框,如截图所示。我想使用xlsxwriter应用条件格式,如果列“B”值为“Total”,则使列“C”的值为粗体。以下代码似乎不起作用

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

这是我更新的代码:

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"})
python-3.x xlsxwriter
1个回答
1
投票

在XlsxWriter中使用条件格式的关键是首先弄清楚你想在Excel中做什么。

在这种情况下,如果要根据另一个单元格中的值格式化单元格,则需要使用“公式”条件格式类型。您还需要确保获得范围和绝对值(带有$符号的值)正确。

这是一个基于您的代码的工作示例:

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()

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.