如何使用openpyxl设置图表绘图区域的背景颜色

Par*_*ria 1 python charts styling openpyxl

我想更改图表的背景颜色,如本例所示,使用 openpyxl。

在谷歌小组讨论中,我发现了以下代码片段:

from openpyxl.chart.shapes import GraphicalProperties 

props = GraphicalProperties(solidFill="999999") 
chart.graphical_properties = props 
chart.plot_area.graphical_properties = props
Run Code Online (Sandbox Code Playgroud)

但保存到excel文件时,它对图表没有任何影响。

Fri*_*ahn 6

这个功能在以前版本的 openpyxl 中似乎被破坏了,并且在 2.4.7 版中得到修复。要获得如图所示的结果,您需要更改 的纯色填充颜色plot_area

from openpyxl import Workbook
from openpyxl.chart import BarChart
from openpyxl.chart.shapes import GraphicalProperties

wb = Workbook()
ws = wb.active

chart = BarChart()

props = GraphicalProperties(solidFill="999999") 
chart.plot_area.graphicalProperties = props

ws.add_chart(chart, "A1")
wb.save("bar.xlsx")
Run Code Online (Sandbox Code Playgroud)

请注意:保存图形属性的成员对象chartchart.graphical_properties,而在 plot_area 中它被命名plot_area.graphicalProperties- 它本身就是 的别名plot_area.spPr

您需要确保访问正确的成员以创建一个有效的数据结构,该结构在 Excel 文件中看起来确实如您所愿。