Python's pptx add content to achieve and delete (mobile) Page Action

Background problem

A large number of tables of data need to be generated ppt file in the specified format, content and form of text-based, inclusive and content pages have a fixed format. Bloggers are not familiar with VBA operations, hope to complete the automation with Python template.

The basic idea

  1. Use xlrdmodule reads the contents of the file xlsx
  2. Use pptxmodule to complete modification ppt

Module version

When used herein, the complete version of the module as Python

pip install xlrd==1.2.0 python-pptx==0.6.18

Implementation

Data read

Xls read about refer to my blog: Python module to read the xlrd xls files and error to solve

Insert page

There are many online reference material about pptx, and soon you can get started and create a new slide page (slide):

from pptx import Presentation
prs = Presentation('template.pptx')

def new_slide(idx):
    'Add slide with layout, 0 = title, 1 = content, 2 = ending'
    layout = prs.slide_layouts[idx]
    slide = prs.slides.add_slide(layout)
    return slide

The code generation support blank pages according to different slide layout (layout), as a template defines the end of the content of the title 2 0. Specific layout can ppt View menu - [Edit] in the slide master.

Defects: New slide will be automatically added to the end of the page, unable to move.

Write to

Pptx files on the nature Office after 2007 is a structured xml archive, and xml in paragraph determines the elements of each page template, content, format, font, size, position, etc., so by searching through the xml file different content to quickly locate the field to be modified.

Each element in the ppt abstract shape, to form, my plan is to do the format in the template and use the copy to a new page deepcopy modify the content.

from copy import deepcopy

slide = new_slide(1) #content slide
slide.shapes.title.text = '本页标题'
el = prs.slides[1].shapes[2].element #table in template
slide.shapes._spTree.insert_element_before(deepcopy(el)) #duplicate
table = slide.shapes[1].table #table in new slide
table.cell(1,1).text_frame.paragraphs[0].runs[0].text = '表格内容'

Delete page

The official pointed out that issue can not be moved slide remove + insert indirectly, more complicated.
Simplify the problem: the tail Add new content page and knot the end of most pages, after deleting the template twenty-three.
[Template] beginning[Content] [end of the template template]New content [1] [2] ...... new content [new] end

def del_slide(index):
    slides = list(prs.slides._sldIdLst)
    prs.slides._sldIdLst.remove(slides[index])

Reference Documents

feature: reorder a slide #68

Guess you like

Origin www.cnblogs.com/azureology/p/12349585.html