openpyxl字体条件格式

时间:2015-09-08 07:20:38

标签: python excel fonts conditional-formatting openpyxl

我使用pyopenxl输出一些excel电子表格,我遇到了字体条件格式的问题。我想用红色突出小于0的细胞,这就是我所做的:

from pyopenxl import formatting, styles

red_font = styles.Font(size=self.font_size, bold=bold, color=self.red_color_font)
red_fill = styles.PatternFill(start_color=self.red_color, end_color=self.red_color, fill_type='solid')

self.ws.conditional_formatting.add(
    cell.coordinate,
    formatting.CellIsRule(operator='lessThan', formula=['0'], fill=red_fill, font=red_font)
)

所以我只是为字体和填充创建了样式,并将它们应用于我的单元格。坏的是它不起作用。一旦我从CellIsRule()删除字体格式,一切都恢复正常,我的单元格充满了红色。但问题是我需要改变颜色,有没有人知道我的代码有什么问题?或者也许使用openpyxl?

1 个答案:

答案 0 :(得分:0)

以下代码适用于openpyxl版本2.2.6

from openpyxl import formatting, styles

wb = Workbook()
ws = wb.active

red_color = 'ffc7ce'
red_color_font = '9c0103'

red_font = styles.Font(size=14, bold=True, color=red_color_font)
red_fill = styles.PatternFill(start_color=red_color, end_color=red_color, fill_type='solid')

for row in range(1,10):            
    ws.cell(row=row, column=1, value=row-5)
    ws.cell(row=row, column=2, value=row-5)

ws.conditional_formatting.add('A1:A10', formatting.CellIsRule(operator='lessThan', formula=['0'], fill=red_fill, font=red_font))
ws.conditional_formatting.add('B1:B10', formatting.CellIsRule(operator='lessThan', formula=['0'], fill=red_fill))
wb.save("test.xlsx")

显示如下:

enter image description here

对于openpyxl版本2.5.1,CellIsRule现在位于rule内,如下所示:

from openpyxl import formatting, styles, Workbook

wb = Workbook()
ws = wb.active

red_color = 'ffc7ce'
red_color_font = '9c0103'

red_font = styles.Font(size=14, bold=True, color=red_color_font)
red_fill = styles.PatternFill(start_color=red_color, end_color=red_color, fill_type='solid')

for row in range(1,10):            
    ws.cell(row=row, column=1, value=row-5)
    ws.cell(row=row, column=2, value=row-5)

ws.conditional_formatting.add('A1:A10', formatting.rule.CellIsRule(operator='lessThan', formula=['0'], fill=red_fill, font=red_font))
ws.conditional_formatting.add('B1:B10', formatting.rule.CellIsRule(operator='lessThan', formula=['0'], fill=red_fill))
wb.save("test.xlsx")