请教一下怎么给excel表每列前3大数值对应单元格分别着不同颜色

请大神指教,有什么好方法?

讨论数量: 1
Jason990420

Example Code,

from random import randint

from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill

# foreground - All in white
fg_colors = [
    Font(color='FFFFFF', bold=True),
    Font(color='FFFFFF', bold=True),
    Font(color='FFFFFF', bold=True),
]

# background - Red for 1st, blue for 2nd, magenta for 3rd
bg_colors = [
    PatternFill(start_color='FF0000', end_color='FF0000', fill_type="solid"),
    PatternFill(start_color='0000FF', end_color='0000FF', fill_type="solid"),
    PatternFill(start_color='FF00FF', end_color='FF00FF', fill_type="solid"),
]

wb = Workbook()     # wn = Workbook('test.xlsx')
ws = wb["Sheet"]

# Create random data in worksheet
for y, col in enumerate(ws.iter_cols(min_row=1, max_col=5, max_row=10)):
    for x, cell in enumerate(col):
        cell.value = randint(0, 1000)

# Find where to paint colors
for col in ws.iter_cols():
    cell_list = list(sorted(col, key=lambda cell:cell.value, reverse=True))
    for i, cell in enumerate(cell_list[:3]):
        cell.font = fg_colors[i]
        cell.fill = bg_colors[i]

# Save workbook
wb.save('test.xlsx')

Python

2周前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!