简体   繁体   中英

openpyxl color cells based on value from another column

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()

I would like to color rows in my 1st column based on their value - all the same values in one color (1,1,1 in red, then 2 in separate color, 3,3 in some other color, 4 in another color etc.). I made the list2, so i can check if rows in list1 have same values (comparison).

I tried something like this:

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'

Nothing. I tried dataframe styler, but styler cannot iterate.

Any thoughts? Much appreciated.

The following creates a dataframe from some data, creates an openpyxl ExcelWriter. It then uses a colourmap from Matplotlib to give you a range of colours. For each unique value it assigns the next value from the colormap, starting with red:

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) 

This would give you an Excel spreadsheet something looking like:

Excel输出示例

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM