用openpyxl可以,示例代码,在颜色设定上可以根据自己需要作更改。
import openpyxl
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font
wb=openpyxl.load_workbook('t1.xlsx',data_only=True)
ws=wb['Sheet1']
def rgb(x,max):
r = int(x*255/max)
g = 255-int(x*255/max)
color="".join([str(hex(x)).replace("x", "0")[-2:] for x in (r,g,0)])
return color
def fill(start,end):
dl = []
for row in ws[start:end]:
dl.extend([x.value for x in row])
max_0=max(dl)
for cell in ws[start:end]:
for c in cell:
c.fill=PatternFill('solid',fgColor=f'{rgb(c.value,max_0)}')
starts=['B2','G2']
ends=['F11','G11']
for start,end in zip(starts,ends):
fill(start, end)
wb.save('t2.xlsx')
结果: