openpyxl颜色单元格基于另一列的值

时间:2017-11-17 14:44:37

标签: python pandas openpyxl

import pandas as pd 
from openpyxl import Workbook 
from pandas import ExcelWriter import openpyxl

wb = Workbook() 
sheet = wb.active 
writer = ExcelWriter('path\\test.xlsx')

list1 = [1,1,1,2,3,3,4,5]
list2 = [1,2,2,2,3,4,4,5]

comparison = [i == j for i,j in zip(list1,list2)]
comparison Out[76]: [True, False, False, True, True, False, True, True]

df = pd.DataFrame(list1,list2)

dataframe_spotovi.to_excel(writer,'Jazler spotovi') 
writer.save()

我想根据它们的值为第一列中的行着色 - 一种颜色中的所有相同值(1,1,1为红色,然后2为单独颜色,3,3为其他颜色,4 in另一种颜色等)。 我创建了list2,所以我可以检查list1中的行是否具有相同的值(比较)。

我试过这样的事情:

for rows in sheet.iter_rows():
    for cell in rows:
        for a, b in zip(mirko, darko):
            if a == b:
                cell.fill = PatternFill(bgColor="FFC7CE", fill_type = "solid")
    else:
        color = 'FFBB00'

无。我尝试过dataframe styler,但是styler无法迭代。

有什么想法?非常感谢。

1 个答案:

答案 0 :(得分:0)

以下内容从某些数据创建数据框,创建openpyxl ExcelWriter。然后它使用Matplotlib的colourmap为您提供一系列颜色。对于每个唯一值,它从colormap指定下一个值,从红色开始:

import pandas as pd
import openpyxl
from openpyxl.styles import PatternFill
import matplotlib
import matplotlib.cm as cm
import numpy as np

data = [
    [1, 'test', 1],
    [1, 'test', 2],
    [1, 'test', 3],
    [2, 'test', 4],
    [3, 'test', 5],
    [3, 'test', 6],
    [4, 'test', 7],
    [5, 'test', 8]]

write_path = "output.xlsx"
df = pd.DataFrame(data, columns=["value", "comment", "index"])
unique = np.unique(df['value']).shape[0] + 1

with pd.ExcelWriter(write_path) as writer:
    df.to_excel(writer, sheet_name="Sheet1", index=False)

wb = openpyxl.load_workbook(write_path)
ws = wb.get_sheet_by_name("Sheet1")   

# Create a color map
tohex = lambda r,g,b,a: '%02X%02X%02X%02X' % (a,r,g,b)
gist_rainbow = cm.gist_rainbow(np.linspace(0, 1, unique))
gist_rainbow = np.array(gist_rainbow * 255, dtype=int)
gist_rainbow = iter([tohex(*gist_rainbow[i,:]) for i in range(unique)])
colours = {}
next_colour = next(gist_rainbow)    # get the next colour in the colormap

for cells in ws.iter_rows(min_row=2, min_col=1, max_col=1):
    cell = cells[0]

    try:
        colour = colours[cell.value]
    except KeyError:
        colours[cell.value] = next_colour
        colour = next_colour
        next_colour = next(gist_rainbow)    # get the next colour in the colormap

    cell.fill = PatternFill(start_color=colour, end_color=colour, fill_type='solid')

wb.save(write_path) 

这会给你一个Excel电子表格,如:

Example Excel output