我正在尝试重新组织下面的代码
from pptx import Presentation
from pptx.dml.color import RGBColor
from pptx.enum.chart import XL_LABEL_POSITION
from pptx.util import Pt
prs = Presentation('test.pptx')
for slide in prs.slides:
for shape in slide.shapes:
if not shape.has_chart:
continue
chart = shape.chart
for series in chart.series:
for point, value in zip(series.points, series.values):
if value >= 7.5:
fill = point.format.fill
fill.solid()
fill.fore_color.rgb = RGBColor(0, 176, 80)
elif value < 7.5 and value >= 3.5:
fill = point.format.fill
fill.solid()
fill.fore_color.rgb = RGBColor(255, 192, 0)
data_label = point.data_label
data_label.position = XL_LABEL_POSITION.CENTER
font = data_label.font
font.color.rgb = RGBColor(0, 0, 0)
font.size = Pt(9)
elif value <3.5 and value > 1:
fill = point.format.fill
fill.solid()
fill.fore_color.rgb = RGBColor(255, 0, 0)
prs.save('testoutput.pptx')
输入以下代码
from pptx import Presentation
from pptx.dml.color import RGBColor
from pptx.enum.chart import XL_LABEL_POSITION
from pptx.util import Pt
prs = Presentation('test.pptx')
for slide in prs.slides:
for shape in slide.shapes:
if not shape.has_chart:
continue
chart = shape.chart
for series in chart.series:
for point, value in zip(series.points, series.values):
fill = point.format.fill
fill.solid()
data_label = point.data_label
font = data_label.font
if value >= 7.5:
fill.fore_color.rgb = RGBColor(0, 176, 80)
elif value < 7.5 and value >= 3.5:
fill.fore_color.rgb = RGBColor(255, 192, 0)
data_label.position = XL_LABEL_POSITION.CENTER
font.color.rgb = RGBColor(0, 0, 0)
font.size = Pt(9)
elif value <3.5 and value > 1:
fill.fore_color.rgb = RGBColor(255, 0, 0)
prs.save('testoutput.pptx')
其中变量预先分配,然后在if语句的其余部分使用(填充、数据标签、字体)。对我来说,代码中的一切看起来都很好,但我显然遗漏了一些东西,因为输出是不同的:
正在操作的原始幻灯片(test.pptx)
代码1的正确输出:
代码2的输出不正确:
也许与直觉相反,一系列的“点”(通常)在您访问它之前并不存在。因此,对点进行迭代是一种破坏性操作,因为某些图表标记(在本例中为条形图)属性的继承被破坏
PowerPoint通过在创建时将所有当前值指定给该点来解决此问题。在UI中,通过选择单个栏并对其进行编辑来创建点
因此,需要为访问的每个点指定某些属性。通过分别遍历值,然后仅访问要更改的点,可以对此进行选择
可能是这样的:
但一旦访问该点,就需要设置所有不需要默认值的属性
相关问题 更多 >
编程相关推荐