示例结果:
theme=1, tint=0.249977111117893
origin_hex_color 000000
final_rgb_color is (63, 63, 63)
theme=2, tint=-0.749961851863155
origin_hex_color E7E6E6
final_rgb_color is (57, 57, 57)
theme=4, tint=0.399945066682943
origin_hex_color 4472C4
final_rgb_color is (142, 170, 219)
import openpyxl
COLOR_INDEX = ('', '000000', 'E7E6E6', '44546A', '4472C4', 'ED7D31') # 预设色没写全
wb = openpyxl.load_workbook('./t.xlsx', data_only=True)
fs = wb.active
fs_count_row = fs.max_row
fs_count_col = fs.max_column
def hex_to_rgb(origin_hex_color):
# Convert hex color code to RGB tuple
r = int(origin_hex_color[0:2], 16)
g = int(origin_hex_color[2:4], 16)
b = int(origin_hex_color[4:6], 16)
return (r, g, b)
def adjust_color(rgb_color, tint):
r, g, b = rgb_color
if tint > 0:
# Tint is positive, lighten the color
r_adjusted = int(r + (255 - r) * tint)
g_adjusted = int(g + (255 - g) * tint)
b_adjusted = int(b + (255 - b) * tint)
else:
# Tint is negative, darken the color
r_adjusted = int(r * (1 + tint))
g_adjusted = int(g * (1 + tint))
b_adjusted = int(b * (1 + tint))
# Ensure values are within valid RGB range (0-255)
r_final = max(0, min(255, r_adjusted))
g_final = max(0, min(255, g_adjusted))
b_final = max(0, min(255, b_adjusted))
return (r_final, g_final, b_final)
for row in range(1, fs_count_row+1):
for column in range(1, fs_count_col+1):
cell_color = fs.cell(column=column, row=row).fill.fgColor
if cell_color.index == '00000000':
continue
if cell_color.type == 'theme':
theme_color_index = cell_color.theme
origin_hex_color = COLOR_INDEX[theme_color_index]
else:
origin_hex_color = cell_color.rgb
origin_rgb_color = hex_to_rgb(origin_hex_color)
tint = cell_color.tint
final_rgb_color = adjust_color(origin_rgb_color, tint)
print("theme={theme}, tint={tint}".format(
theme=theme_color_index, tint=tint))
print("origin_hex_color", origin_hex_color)
print("final_rgb_color is {final_rgb_color}".format(
final_rgb_color=final_rgb_color))