Python Pptx - Modify Existing Table

2020-06-27 05:43发布

I'm very new to the python-pptx module, so please excuse my ignorance. I'm trying to modify an existing table in a PowerPoint file, but I don't see anywhere in the documentation where I can do this.

I see where you can use the add_table() method to create a new table, but I only need to modify an existing table with data from a Pandas dataframe.

2条回答
贪生不怕死
2楼-- · 2020-06-27 06:26

There are multiple ways to select a shape in python-pptx. The best way to go around this is to know the id of the shape, you can get the id either by opening up the xml and finding the shape, or you can loop over all the shapes in the slide and print the id that way. However, you can still select the shape without knowing its id.

If you know the shape id, you can search the slide for that shape's id, something like this will return the shape you want.

for shape in slide.shapes:
    if shape.shape_id == shape_id:
        return shape

If you don't know the shape id, there are a few ways to get the shape, they're all a bit hacky, but they will all work.

  • If there's only one instance of that shape type in the slide, this is straight forward, just search for a shape with that shape type in the slide.
for shape in slide.shapes:
    if shape.shape_type == your_shape_type:
        return shape
  • If there's more than one instance of that shape type in the slide (i.e there's more than one table) it gets more complicated, you can set up some identifying feature (put placeholder text). For instance, I set up a chart with a placeholder series name, and this is how I select it in python.
for shape in slide.shapes:
    if shape.has_chart:
        if str([s.name for s in shape.chart.series][0]) == series_name:
            return shape
查看更多
Anthone
3楼-- · 2020-06-27 06:31

Once you get the shape id, as Saleh mentioned, you can modify table cells like this:
For slide 0, the shape id 6, changing the first cell (0,0), to 'Pina Colada':

Presentation('yourpowerpoint.pptx').slides[0].shapes[6].table.cell(0,0).text= 'Pina Colada'
查看更多
登录 后发表回答