How to set Background Color of Plot Area of Chart

2019-03-04 04:09发布

问题:

I would like to change the background color of a chart, as in this example, using openpyxl.

In a google group discussion I found the following code snippet:

from openpyxl.chart.shapes import GraphicalProperties 

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

but it does not have any effect on the chart when saved to the excel file.

回答1:

This functionality was seemingly broken in a previous version of openpyxl and is fixed as of release 2.4.7. To achieve the result as illustrated in your picture you need to change the solid fill color of the 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")

Please note: the member object holding the graphical properties of chart is chart.graphical_properties, whereas in plot_area it is named plot_area.graphicalProperties - which is itself an alias for plot_area.spPr.

You need to be sure to access the proper member to create a valid data structure that does look as you expect it to in the Excel file.