我正在尝试在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)
但是,用于条形图样式的对象是仅接受rgb值的openpyxl.drawing.colors对象。
在Excel应用程序中使用主题颜色设置栏的样式绝对是可能的。从理论上讲,保存后我可以使用一些后期制作脚本来编辑excel文件的原始xml,但这效率很低。
在openpyxl中有什么方法可以做到这一点?
在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")
输出