作为一个小爱好项目的一部分,我正在try 在上传到Google Drive之前为Excel工作表中的单元格添加一些格式.

单元格可以是0、1或2,根据值的不同,我会应用 colored颜色 (分别为白色、黑色或灰色).

以下是我的try :

from openpyxl import load_workbook
from openpyxl.styles import PatternFill
from openpyxl.styles.differential import DifferentialStyle
from openpyxl.formatting.rule import Rule
from openpyxl.cell.cell import Cell

# Load the Excel workbook
workbook = load_workbook('output.xlsx')

# Select the desired sheet by name or index
sheet = workbook['Sheet1']  # Replace 'Sheet1' with the actual sheet name

# Create the conditional formatting rules
rules = [
    {
        'value': 1,
        'fill_color': '00000000'  # Black
    },
    {
        'value': 2,
        'fill_color': 'FF808080'  # Solid Grey
    }
]

for rule in rules:
    fill = PatternFill(start_color=rule['fill_color'], end_color=rule['fill_color'], fill_type='solid')

    # Apply conditional formatting rule
    for row in sheet.iter_rows(min_row=2, values_only=True):  # Start from the second row assuming headers are in the first row
        for cell in row:
            if isinstance(cell, Cell) and cell.value == rule['value']:
                cell.fill = fill

# Save the modified workbook with conditional formatting
workbook.save('output_formatted.xlsx')

代码似乎可以运行,但OutputFormatted.xlsx似乎没有任何格式.你知道我哪里出问题了吗,或者你能建议一个更好的方法来解决这个问题吗?

我预计输出如下所示:

image of excel sheet cells color coded scheme

如果有帮助,这里是前几行数据的摘录(提前为糟糕的格式道歉):

normalM normalF shinyM  shinyF  darkM   darkF   goldenM goldenF
0   0   1   0   1   0   1   0
0   0   0   0   0   0   1   0
1   0   0   1   1   0   0   0
0   0   1   1   1   1   1   1
1   0   1   1   1   0   1   0
1   2   0   2   1   2   1   2
1   2   0   2   1   2   1   2
1   1   1   1   0   1   1   1
0   0   0   0   0   0   0   0
0   0   1   0   0   0   1   1
0   1   0   0   1   0   0   1

任何智慧的话语都将不胜感激.谢谢. PS:我也了解Pandas ,如果你有什么建议可以用Pandas 来解决这个问题,我很乐意try 一下.

推荐答案

You mention Conditional Formatting Rules in the code so not really sure if you are trying to achieve this using CF or just loop through and change the fill based on the value in each cell.
In a case like this, generally CF is better. It's only necessary to set the range to cover as many or few cells as required rather than loop every cell and if you want to change the cell values later they will update dynamically.

If CF is your preference you'd want something like this;
Assumes the range C1 to J12 (with row 1 being the Header row -
EDIT
I didn't bother with it since there were only two rules, but if you wanted to include more fills then you can change the code to add each CF rule in a loop as shown in the updated code;

from openpyxl import load_workbook
from openpyxl.styles import PatternFill
from openpyxl.formatting.rule import Rule, CellIsRule

# Create fill
blackFill = PatternFill(start_color='000000', end_color='000001', fill_type='solid')
greyFill = PatternFill(start_color='808080', end_color='808080', fill_type='solid')

# Load the Excel workbook
workbook = load_workbook('output.xlsx')

# Select the desired sheet by name or index
sheet = workbook['Sheet1']  # Replace 'Sheet1' with the actual sheet name

# sheet.conditional_formatting.add('C2:J12',
                                 # CellIsRule(operator='equal', formula=['1'], stopIfTrue=True, fill=blackFill))

# sheet.conditional_formatting.add('C2:J12',
                                 # CellIsRule(operator='equal', formula=['2'], stopIfTrue=True, fill=greyFill))

colour_dict = {1: blackFill, 2: greyFill}
for x in range(1, 3):
    sheet.conditional_formatting.add('C2:J12',
                                     CellIsRule(operator='equal',
                                                formula=[x],
                                                stopIfTrue=True,
                                                fill=colour_dict[x]
                                                )
                                     )

workbook.save('output_formatted.xlsx')

从提供的数据中,您将获得如下所示的填充.
如果单元格C2更改为1,则填充将变为黑色,如果更改为2,则填充将变为灰色.

Example output from provided data

Python相关问答推荐

如何在PIL、Python中对图像应用彩色面膜?

将HLS纳入媒体包

Python在tuple上操作不会通过整个单词匹配

比较2 PD.数组的令人惊讶的结果

如何找到满足各组口罩条件的第一行?

如何在Django基于类的视图中有效地使用UTE和RST HTIP方法?

PyQt5,如何使每个对象的 colored颜色 不同?'

如何调整QscrollArea以正确显示内部正在变化的Qgridlayout?

为什么抓取的HTML与浏览器判断的元素不同?

从嵌套的yaml创建一个嵌套字符串,后面跟着点

Django admin Csrf令牌未设置

如何使用Numpy. stracards重新编写滚动和?

在Python中调用变量(特别是Tkinter)

在极中解析带有数字和SI前缀的字符串

Python—为什么我的代码返回一个TypeError

处理Gekko的非最优解

如何使用matplotlib查看并列直方图

在Django中重命名我的表后,旧表中的项目不会被移动或删除

我可以不带视频系统的pygame,只用于游戏手柄输入吗?''

Pandas数据框上的滚动平均值,其中平均值的中心基于另一数据框的时间