You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在openpyxl中为多行图表标题设置每行不同颜色

解决Excel图表多行标题每行设置不同颜色的问题

要实现多行标题每行独立设置样式,不能直接用字符串拼接\n的方式,需要利用**富文本(RichText)**对象,将每行标题作为独立文本块分别配置字符属性。以下是基于openpyxl库的具体实现方案:

  • 先导入所需类:

    from openpyxl.chart.text import RichText, TextBlock
    from openpyxl.drawing.text import CharacterProperties
    
  • 定义两行标题的文本及对应样式:

    # 第一行标题样式(示例:黑色、14号字)
    main_title = "Room: XXX, Sample Type: XXX, Grid: XXX"
    main_style = CharacterProperties(sz=14, rgb="000000")
    
    # 第二行标题样式(示例:红色、12号字)
    sub_title = "Acceptance Criteria: XXX"
    sub_style = CharacterProperties(sz=12, rgb="FF0000")
    
  • 创建富文本对象,组合两个带样式的文本块:

    # 每个TextBlock对应一行,自动实现换行
    rich_title = RichText([
        TextBlock(main_style, main_title),
        TextBlock(sub_style, sub_title)
    ])
    
  • 将富文本对象赋值给图表标题:

    chart.title = rich_title
    

关键说明

  • 颜色值采用无#前缀的RGB十六进制格式,比如蓝色为0000FF,灰色为808080。
  • CharacterProperties还支持设置粗体(b=True)、斜体(i=True)、字体(typeface="微软雅黑")等更多样式。
  • 确保使用的openpyxl版本为2.6.0及以上,旧版本对富文本标题的支持存在局限。

内容的提问来源于stack exchange,提问作者Matt Mennella

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 23:03:20