向 Cell OpenPyXL 添加背景颜色

Adding a background color to Cell OpenPyXL

我试图让我的代码在 "Present" 时在单元格上发出绿色背景,在 "Absent" 时在单元格上发出红色背景。这是我的代码。

ws1.cell(column=1, row=t, value="%s" % blue_student_list)
if (student_check(i)):
    ws1.cell(column=2, row=t, value="%s" % "Present")
else:
    ws1.cell(column=2, row=t, value="%s" % "Absent")

此代码运行完美,我只是想知道如何在单元格后面添加背景颜色。

来自documentation

from openpyxl.styles import PatternFill
        
sheet['A1'].fill = PatternFill(bgColor="FFC7CE", fill_type = "solid")
    

对于 openpyxl 2.5.3,上面的代码不起作用。

尝试后,以下代码有效:

from openpyxl.styles import PatternFill
sheet['A1'].fill = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type = "solid")

正如@Charlie Clark(openpyxl 的合著者)所建议的那样,条件格式可能是更好的方法。 official doc

中的更多信息

如果你想改变背景颜色,从最近的版本开始,关键字 bgcolor 似乎不起作用(在我的例子中,单元格的颜色最终变成黑色)。

相反,您可以使用 start_colorfgColor。例如,两种解决方案都有效:

from openpyxl.styles import PatternFill
from openpyxl.styles.colors import YELLOW

sheet['A1'].fill = PatternFill(start_color="FFC7CE", fill_type = "solid")
sheet['A1'].fill = PatternFill(fgColor=YELLOW, fill_type = "solid")

这适用于 openpyxl V 2.6 及更高版本


from openpyxl.styles import PatternFill

for col_range in range(1, 12):
    cell_title = sheet.cell(1, col_range)
    cell_title.fill = PatternFill(start_color="8a2be2", end_color="8a2be2", fill_type="solid")

这将为 A1 到 K1 的单元格着色

我很难复制单元格的背景颜色(从一本书的标签复制到另一本书的标签...)

在尝试了很多变通方法之后,我发现这个可行:

 from openpyxl.styles import PatternFill
 from openpyxl.styles.colors import COLOR_INDEX
 from copy import copy as shallow_copy, deepcopy as deep_copy
 # .
 # .
 # .
 if from_cell.has_style:
    if isinstance(from_cell.fill.start_color.index, int):
       start_color=COLOR_INDEX[from_cell.fill.start_color.index]

    else: # _sometimes_ a string...
          start_color=from_cell.fill.start_color.index

    end_color=start_color
    to_cell.fill=shallow_copy(PatternFill(fill_type=from_cell.fill.fill_type,
                                          start_color=start_color,
                                          end_color=end_color,
                                          patternType=from_cell.fill.patternType
                                 )
                     )

仅供参考:openpyxl 是一个很棒的产品;我认为很多开发人员都没有意识到使用它的可能性。我会支持这个项目。

我认为可能有一些开发人员误认为它是 anti-open 来源;但 xlsx 文档也由 LibreOffice 呈现...