使用 xlsxwriter 根据条件使字符加粗
make characters bold based on conditionals using xlsxwriter
我有一个 pandas 数据框,如屏幕截图所示。如果列 "B" 的值为 "Total",我想使用 xlsxwriter 应用条件格式以使列 "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"})
这是我更新后的代码:
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"})
在 XlsxWriter 中使用条件格式的关键是先弄清楚你想在 Excel 中做什么。
在这种情况下,如果您想根据另一个单元格中的值设置一个单元格的格式,您需要使用 "formula" 条件格式类型。您还需要确保范围和绝对值(带 $ 符号的)正确。
这是一个基于您的代码的工作示例:
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()
输出:
我有一个 pandas 数据框,如屏幕截图所示。如果列 "B" 的值为 "Total",我想使用 xlsxwriter 应用条件格式以使列 "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"})
这是我更新后的代码:
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"})
在 XlsxWriter 中使用条件格式的关键是先弄清楚你想在 Excel 中做什么。
在这种情况下,如果您想根据另一个单元格中的值设置一个单元格的格式,您需要使用 "formula" 条件格式类型。您还需要确保范围和绝对值(带 $ 符号的)正确。
这是一个基于您的代码的工作示例:
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()
输出: