Python自动根据工作表添加目录并设置标签颜色

import colorsys
import traceback
import zipfile
import xml.etree.ElementTree as ET
from openpyxl import load_workbook
from openpyxl.styles import Alignment, PatternFill
from openpyxl.styles.colors import COLOR_INDEX
from openpyxl.worksheet.hyperlink import Hyperlink

src = "D:\LW\案例.xlsx"

PALETTE = [
    "2A0081",  # 1  深靛蓝
    "B7E7FC",  # 2  浅天青
    "FFD3F0",  # 3  樱花粉
    "F5C700",  # 4  正金黄
    "BA1650",  # 5  深玫红
    "EF525A",  # 6  珊瑚红
    "C4AF40",  # 7  橄榄黄
    "E21BD9",  # 8  荧光洋紫
    "ECA723",  # 9  橘金色
    "966884",  # 10 玫瑰灰紫
    "379223",  # 11 森林绿
    "F24245",  # 12 亮正红
    "383BA8",  # 13 钴宝蓝
    "0FBC62",  # 14 翡翠绿
    "66F60B",  # 15 荧光草绿
    "24C0D5",  # 16 青湖蓝
    "C0353A",  # 17 砖红色
    "80BE5C",  # 18 豆绿色
    "6F00AD",  # 19 深紫罗兰
    "577999",  # 20 钢灰色蓝
    "539837",  # 21 深草绿
    "139F91",  # 22 墨青绿
    "481A1C",  # 23 深褐红
    "E9E5DF",  # 24 暖米白
    "C85802",  # 25 焦糖橘棕
    "AB521E",  # 26 赭石棕
    "93FFD2",  # 27 薄荷浅绿
    "BC50EE",  # 28 兰花亮紫
    "E66861",  # 29 鲑鱼红
    "2336E9",  # 30 宝蓝色
]
# 主题XML命名空间
NS = {'a': 'http://schemas.openxmlformats.org/drawingml/2006/main'}


#自动根据工作表添加目录
#同时给工作表标签设置颜色
def generate_toc():
    try:
        wb = load_workbook(src)
        # 如果已经存在目录先删掉
        if "目录" in wb.sheetnames:
            wb.remove(wb["目录"])
        sn = wb.sheetnames
        ws = wb.create_sheet("目录", 0)
        for i, name in enumerate(sn, start=1):
            #color = PALETTE[(i-1) % len(PALETTE)]
            #wb[name].sheet_properties.tabColor = color
            if wb[name].sheet_properties.tabColor is None:
                color = PALETTE[(i-1) % len(PALETTE)]
                wb[name].sheet_properties.tabColor = color
            else:
                color = tab_color_to_hex(wb[name], src)
            cell_color = ws.cell(row=i, column=1, value="")
            cell_color.fill = PatternFill(start_color=color, end_color=color, fill_type="solid")
            cell_idx = ws.cell(row=i, column=2, value=i)
            cell_idx.alignment = Alignment(horizontal="center", vertical="center")
            cell_name = ws.cell(row=i, column=3, value=name)
            cell_name.hyperlink = Hyperlink(ref=cell_name.coordinate, location=f"'{name}'!A1")
            cell_name.style = "Hyperlink"
            cell_name.alignment = Alignment(horizontal="center", vertical="center")
            ws.row_dimensions[i].height = 22
        ws.column_dimensions["A"].width = 4
        ws.column_dimensions["B"].width = 6
        ws.column_dimensions["C"].width = 32
        wb.save(src)
        print(f"✅ 目录生成成功!共列出 {len(sn)} 个工作表。")
    except PermissionError:
        print("❌ 保存失败:文件可能正在被 Excel 或其他程序占用,请关闭后重试。")
    except Exception as e:
        traceback.print_exc()  # 直接打印到控制台


def _parse_argb_hex(hex_str):
    hex_str = hex_str.upper().strip()
    if len(hex_str) == 8:
        hex_str = hex_str[2:]
    if len(hex_str) != 6:
        raise ValueError(f"无法解析颜色值: {hex_str}")
    return int(hex_str[0:2], 16), int(hex_str[2:4], 16), int(hex_str[4:6], 16)


def _rgb_to_hex(r, g, b):
    return f"{r:02X}{g:02X}{b:02X}"


def _apply_tint(r, g, b, tint):
    h, l, s = colorsys.rgb_to_hls(r / 255.0, g / 255.0, b / 255.0)

    tint = float(tint) if tint is not None else 0.0
    LUM = 255.0

    lum = l * LUM

    if tint < 0:
        lum = lum * (1.0 + tint)
    elif tint > 0:
        lum = lum * (1.0 - tint) + (LUM - LUM * (1.0 - tint))

    l = lum / LUM
    l = max(0.0, min(1.0, l))

    nr, ng, nb = colorsys.hls_to_rgb(h, l, s)

    r_out = int(round(max(0, min(255, nr * 255))))
    g_out = int(round(max(0, min(255, ng * 255))))
    b_out = int(round(max(0, min(255, nb * 255))))

    return r_out, g_out, b_out


def _get_theme_color_from_zip(wb_path, theme_index, tint):
    # 主题色顺序:lt1, dk1, lt2, dk2, accent1~6, hlink, folHlink
    slot_names = [
        "a:lt1", "a:dk1", "a:lt2", "a:dk2",
        "a:accent1", "a:accent2", "a:accent3",
        "a:accent4", "a:accent5", "a:accent6",
        "a:hlink", "a:folHlink",
    ]

    if theme_index < 0 or theme_index >= len(slot_names):
        return None

    tag = slot_names[theme_index]

    with zipfile.ZipFile(wb_path) as z:
        names = [n for n in z.namelist() if "theme" in n.lower() and n.endswith(".xml")]
        for name in names:
            try:
                data = z.read(name)
                root = ET.fromstring(data)
            except Exception:
                continue

            scheme = root.find(".//a:clrScheme", NS)
            if scheme is None:
                continue

            # 按 clrScheme 子元素顺序取色,而不是硬编码 accent1~accent9
            children = list(scheme)
            if theme_index >= len(children):
                continue

            node = children[theme_index]
            if node is None or not node.tag.endswith("}" + tag.split(":")[1]):
                # 如果顺序对不上,再按 tag 找一次
                node = scheme.find(tag, NS)
                if node is None:
                    continue

            srgb = node.find("a:srgbClr", NS)
            sys_clr = node.find("a:sysClr", NS)

            if srgb is not None:
                val = srgb.get("val")
                if not val:
                    continue
                r, g, b = _parse_argb_hex(val)
            elif sys_clr is not None:
                last_clr = sys_clr.get("lastClr")
                if not last_clr:
                    continue
                r, g, b = _parse_argb_hex(last_clr)
            else:
                continue

            r, g, b = _apply_tint(r, g, b, tint)
            return _rgb_to_hex(r, g, b)

    return None

# 把主题颜色转换成RGB
def tab_color_to_hex(ws, wb_path=None):
    tab_color = getattr(ws.sheet_properties, "tabColor", None)
    if tab_color is None:
        return None

    if tab_color.type == "rgb":
        try:
            r, g, b = _parse_argb_hex(tab_color.rgb)
            return _rgb_to_hex(r, g, b)
        except Exception:
            return None

    if tab_color.type == "indexed":
        idx = tab_color.indexed
        if idx is None:
            return None
        try:
            hex_color = COLOR_INDEX[idx]
        except IndexError:
            return None
        if not hex_color:
            return None
        try:
            r, g, b = _parse_argb_hex(hex_color)
            return _rgb_to_hex(r, g, b)
        except Exception:
            return None

    if tab_color.type == "theme":
        theme = tab_color.theme
        tint = tab_color.tint if tab_color.tint is not None else 0.0
        if theme is None:
            return None
        if wb_path:
            return _get_theme_color_from_zip(wb_path, theme, tint)
        return None

    return None

#主程序
def main():
    generate_toc()

# 程序入口
if __name__ == '__main__':
    main()

  

posted @ 2026-10-27 21:05  liw66  阅读(22)  评论(0)    收藏  举报