如何使用openpyxl设置图表绘图区的背景颜色
How to set Background Color of Plot Area of Chart using openpyxl
我想使用 openpyxl 更改图表的背景颜色,as in this example。
在 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
.
的别名
您需要确保访问正确的成员以创建一个有效的数据结构,该结构在 Excel 文件中确实符合您的预期。
我想使用 openpyxl 更改图表的背景颜色,as in this example。
在 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
.
您需要确保访问正确的成员以创建一个有效的数据结构,该结构在 Excel 文件中确实符合您的预期。