openpyxl - 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中,当整体改变图表时,它实际上被称为“样式”,而不是主题。
使用此处提供的示例,我突出显示了<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")
输出
推荐阅读
- node.js - 如何读取我从服务器获取的图像作为缓冲区?
- python - 如何修复模板语法错误?
- python - 我的 python 代码在单人学习应用程序上运行正常,但在电脑上运行不正常
- ios - 在 macOS 上解码后,在 iOS 上编码为 Data 的 Int 数为零
- python - 当我不保存时,Python 中的 IDLE 编辑器不会运行我的代码
- azure-eventhub - 为什么捕获的 SystemProperties 和 Properites 的 azure eventthub 信息为空?
- linux - 如何将 bash 脚本分配给 Linux 中的键盘键
- angular - Angular 8拦截调用刷新令牌
- react-native - React-Native:在为输入字符串“h”更新 RNSVGPath 类型的阴影节点中的属性“d”时出错
- r - 一次将数据帧子集到数据帧列表中