How to set Background Color of Plot Area of Chart using openpyxl

谁都会走 提交于 2019-12-20 06:32: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.



来源:https://stackoverflow.com/questions/43329669/how-to-set-background-color-of-plot-area-of-chart-using-openpyxl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!