python openpyxl 获取单元格背景色,含预设 theme 颜色转换

示例结果:

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

泡泡码客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值