如何使用openpyxl和python3为excel工作表中的一系列单元格(列和行)指定字体颜色?

如何使用openpyxl和python3为excel工作表中的一系列单元格(列和行)指定字体颜色?,python,python-3.x,pandas,openpyxl,xlsxwriter,Python,Python 3.x,Pandas,Openpyxl,Xlsxwriter,我想使用openpyxl将红色设置为excel工作表中的一系列单元格(一列到另一列) 我能够从官方文档中找到如何给单元格赋予某种颜色,但我无法找出如何给出一个范围 基本上,我希望使用openpyxl实现如下功能: inheritance_cell_format = wb.add_format() inheritance_cell_format.set_font_color('red') ws.conditional_format( 0, skip_cols-2, ws.max_row, skip

我想使用
openpyxl
将红色设置为excel工作表中的一系列单元格(一列到另一列)

我能够从官方文档中找到如何给单元格赋予某种颜色,但我无法找出如何给出一个范围

基本上,我希望使用openpyxl实现如下功能:

inheritance_cell_format = wb.add_format()
inheritance_cell_format.set_font_color('red')
ws.conditional_format( 0, skip_cols-2, ws.max_row, skip_cols-1, { 'type': 'cell', 'criteria': '=', 'value': '⇒', 'format': inheritance_cell_format } )
以上代码段在xlsxwriter中工作


显然,到目前为止,我在第一行收到一个错误,指出工作簿没有属性“
add\u format()

您可以使用方法.iter\u rows()或iter\u cols()为范围着色。 您可以导入PatternFill来为其着色

import openpyxl as px
from openpyxl.styles import PatternFill

wb = px.load_workbook(file) #imports file
ws = wb.active #Active sheet (first one)
for row in sheet.iter_rows(min_row=1, max_col=3, max_row=2): #max row and col (range)
   for cell in row:
       cell.fill = PatternFill(start_color="FF0000", fill_type = "solid") #html colors


wb.save(file)