【问题标题】:Openpyxl: use excel theme colors in chartOpenpyxl:在图表中使用 excel 主题颜色
【发布时间】:2020-02-16 19:29:25
【问题描述】:

我正在尝试在 openpyxl 创建的图表中使用 Excel 的主题颜色。我想要主题颜色,以便在用户加载新主题时可以更新整个工作簿的颜色。

Openpyxl 具有使用 rgb 值对条形图中的系列条进行着色的功能,如下所示。

import openpyxl
wb = openpyxl.load_workbook('myBook.xlsx')
ws = wb["chartSheet"]
chart = openpyxl.chart.BarChart()
chart.type = "col"
data = Reference(ws, min_col=2, min_row=1, max_row=7, max_col=3)
cats = Reference(ws, min_col=1, min_row=2, max_row=7)
chart.add_data(data, titles_from_data=True)
chart.set_categories(cats)


chart.series[0].graphicalProperties.solidFill = 'FFFF66'


ws.add_chart(chart, "B2")

为了给单元格的填充颜色设置样式,有一个 openpyxl.styles.colors.Color 对象,可让您根据主题定义颜色,如下所示:openpyxl.styles.colors.Color(theme=7)

但是,用于条形图样式的对象是 openpyxl.drawing.colors 对象,它只接受 rgb 值。

绝对可以在 Excel 应用程序中使用主题颜色设置条形样式。理论上,我可以使用一些后期制作脚本来编辑保存后的 excel 文件的原始 xml,但这将是非常低效的。

有什么方法可以在 openpyxl 中实现这一点吗?

【问题讨论】:

    标签: openpyxl


    【解决方案1】:

    在openpyxl中,当整体改变图表时,它实际上被称为“样式”,而不是主题。

    使用here提供的示例,我突出显示了<chartnumber>.style值的修改。

    from openpyxl import Workbook
    from openpyxl.chart import BarChart, Series, Reference
    
    wb = Workbook(write_only=True)
    ws = wb.create_sheet()
    
    rows = [
        ('Number', 'Batch 1', 'Batch 2'),
        (2, 10, 30),
        (3, 40, 60),
        (4, 50, 70),
        (5, 20, 10),
        (6, 10, 40),
        (7, 50, 30),
    ]
    
    
    for row in rows:
        ws.append(row)
    
    
    chart1 = BarChart()
    chart1.type = "col"
    chart1.style = 10 #Style Modification
    chart1.title = "Bar Chart"
    chart1.y_axis.title = 'Test number'
    chart1.x_axis.title = 'Sample length (mm)'
    
    data = Reference(ws, min_col=2, min_row=1, max_row=7, max_col=3)
    cats = Reference(ws, min_col=1, min_row=2, max_row=7)
    chart1.add_data(data, titles_from_data=True)
    chart1.set_categories(cats)
    chart1.shape = 4
    ws.add_chart(chart1, "A10")
    
    from copy import deepcopy
    
    chart2 = deepcopy(chart1)
    chart2.style = 11 #Style Modification
    chart2.type = "bar"
    chart2.title = "Horizontal Bar Chart"
    
    ws.add_chart(chart2, "G10")
    
    
    chart3 = deepcopy(chart1)
    chart3.type = "col"
    chart3.style = 12 #Style Modification
    chart3.grouping = "stacked"
    chart3.overlap = 100
    chart3.title = 'Stacked Chart'
    
    ws.add_chart(chart3, "A27")
    
    
    chart4 = deepcopy(chart1)
    chart4.type = "bar"
    chart4.style = 13 #Style Modification
    chart4.grouping = "percentStacked"
    chart4.overlap = 100
    chart4.title = 'Percent Stacked Chart'
    
    ws.add_chart(chart4, "G27")
    
    wb.save("bar.xlsx")
    

    输出

    【讨论】:

    • 是的,chart.style 属性允许您从 Excel 的图表预设之一中进行选择。也就是说,它不允许您使用主题颜色为特定系列着色。例如,如果您希望一个系列是黑色的,而另一个系列是基于某个主题的,那么您无法使用 .style
    猜你喜欢
    • 2022-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-11
    • 2020-02-17
    • 1970-01-01
    相关资源
    最近更新 更多