Nho*_*hor 5 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)
)
Run Code Online (Sandbox Code Playgroud)
因此,我只是为字体和填充创建样式,并将其应用于我的单元格。不好的是,它不起作用。一旦我从CellIsRule()所有内容中删除了字体格式,一切就恢复了正常,并且我的单元格被红色填充。但问题是我也需要更改颜色,有人知道我的代码有什么问题吗?或者也许与openpyxl?
要突出显示小于零的单元格,您可以在使用openpyxlversion时使用以下代码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")
Run Code Online (Sandbox Code Playgroud)
这显示如下:
对于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")
Run Code Online (Sandbox Code Playgroud)