首页 > 解决方案 > Python,openpyxl,循环使用基于值的单元格的随机 bg 颜色

问题描述

我需要使用openpyxl循环for插入随机背景颜色,基于单元格中的值?

if cell_value = 1 then backgroundcolor = blue (or random color)
if cell_value = 2 then backgroundcolor = red (or random color)
if cell_value = 3 then backgroundcolor = white (or random color)

... etc.

我试过这个。

wb = load_workbook(file)
ws = wb.active

from openpyxl import load_workbook
from openpyxl.styles import PatternFill

for row in ws.iter_rows("A"):
    for cell in row:
        if cell.value == '1':
            ws.cell(row=cell.row, column=1).fill = PatternFill(fgColor="ff33ff", fill_type = "solid")
        elif cell.value == '2':
            ws.cell(row=cell.row, column=1).fill = PatternFill(fgColor="33ffff", fill_type = "solid")
        elif cell.value == '3':
            ws.cell(row=cell.row, column=1).fill = PatternFill(fgColor="ffff55", fill_type = "solid")
        elif cell.value == '4':
            ws.cell(row=cell.row, column=1).fill = PatternFill(fgColor="ff55ff", fill_type = "solid")

...

它正在工作,但我该如何做循环?例如 1000 个值。谢谢。

PS:请在代码中显示我。

标签: pythonfor-loopopenpyxl

解决方案


推荐阅读