如何使用openpyxl设置图表的绘图区域的背景色 [英] How to set Background Color of Plot Area of Chart using openpyxl
问题描述
我想更改图表的背景颜色,如本例所示, ,使用openpyxl.
在一个Google网上论坛讨论中,我找到了以下代码段:
from openpyxl.chart.shapes import GraphicalProperties
props = GraphicalProperties(solidFill="999999")
chart.graphical_properties = props
chart.plot_area.graphical_properties = props
,但是将其保存到excel文件时对图表没有任何影响.
此功能在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")
请注意::拥有chart
图形属性的成员对象是chart.graphical_properties
,而在plot_area中,它被命名为plot_area.graphicalProperties
-它本身是plot_area.spPr
的别名. /p>
您需要确保访问适当的成员以创建一个有效的数据结构,该结构看起来确实像您在Excel文件中所期望的那样.
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.
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.
这篇关于如何使用openpyxl设置图表的绘图区域的背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!