首页 > 解决方案 > Openpyxl:在图表中使用 excel 主题颜色

问题描述

我正在尝试在 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

解决方案


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

使用此处提供的示例,我突出显示了<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")

输出

条形图


推荐阅读