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

How to give font color to a range of cells (columns and rows) in excel worksheet using openpyxl and python3?

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

我能够从官方文档中找到如何为单元格指定特定颜色,但我无法弄清楚如何指定范围。

基本上,我想要这样的东西使用 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_format()

您可以使用 .iter_rows() 或 iter_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)