openpyxl字体条件格式

2024-04-30 01:55:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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?


Tags: selfsize格式字体redexcelfillcolor
1条回答
网友
1楼 · 发布于 2024-04-30 01:55:15

以下代码适用于使用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")

相关问题 更多 >