简介
PPTX 格式的文件本质上是一个 XML 格式的树,所以有个 python-pptx 的包可以解析和读写这个树。只要遍历这棵树就可以将里面相应的内容进行修改,并动态调整里面的内容。如果是图片或者图表,可以在模板里直接将内容关联到外部文件中,直接修改文件,幻灯片中的内容也将实时改变。https://blog.csdn.net/u011932355/article/details/73287248
import pptx
def xml2dict(layout):
root = layout.element
def traverse(root):
children = root.getchildren()
return {
root.tag: {
'children': [traverse(child) for child in children],
'attrib': root.attrib,
'text': root.text
}
}
return traverse(root)
def xml2slimdict(layout, data_head='{http://schemas.openxmlformats.org/drawingml/2006/main}'):
root = layout.element
def traverse(root):
children = root.getchildren()
rst = dict()
if children:
rst['children'] = [traverse(child) for child in children]
if root.text:
rst['text'] = root.text
if rst:
return {root.tag.replace(data_head, ''): rst}
else:
return root.tag.replace(data_head, '')
return traverse(root)
def tree_find(slide, to_find):
route = list()
routes = list()
root = slide.element
def traverse(root):
for i, child in enumerate(root.getchildren()):
route.append(i)
if child.text == to_find:
routes.append(route.copy())
traverse(child)
route.pop()
traverse(root)
routes = [''.join(['[{}]'.format(i) for i in j]) for j in routes]
return routes
def fill_cm(ppt, page, cm, auc):
ppt.slides[page - 1].element[0][0][8][2][2][3][1].text = auc
ppt.slides[page - 1].element[0][0][4][2][0][0][4][2][0][2][1][1].text = cm[0][0]
ppt.slides[page - 1].element[0][0][4][2][0][0][4][3][0][2][1][1].text = cm[0][1]
ppt.slides[page - 1].element[0][0][4][2][0][0][5][2][0][2][1][1].text = cm[1][0]
ppt.slides[page - 1].element[0][0][4][2][0][0][5][3][0][2][1][1].text = cm[1][1]
return ppt
def main(page, cm, auc):
ppt = pptx.Presentation('template.pptx')
ppt = fill_cm(ppt, cm, auc)
ppt.save('result.pptx')