Python Pptx - Modify Existing Table

社会主义新天地 提交于 2020-01-22 16:00:07

问题


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.


回答1:


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'



回答2:


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


来源:https://stackoverflow.com/questions/50841229/python-pptx-modify-existing-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!