1

The (1x2) table in python-pptx has a tr object with the following xml (abbreviated):

<a:tr xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" h="777240">
  <a:tc>
    <a:txBody>
      <a:bodyPr/>
      <a:lstStyle/>
      ...
    </a:txBody>
    <a:tcPr anchor="ctr">
      ...
    </a:tcPr>
  </a:tc>
  <a:tc>
    <a:txBody>
      <a:bodyPr/>
      <a:lstStyle/>
      ...
    </a:txBody>
    <a:tcPr anchor="ctr">
      ...
    </a:tcPr>
  </a:tc>
  <a:extLst>
    <a:ext uri="{0D108BD9-81ED-4DB2-BD59-A6C34878D82A}">
      <a16:rowId xmlns:a16="http://schemas.microsoft.com/office/drawing/2014/main" val="2729466849"/>
    </a:ext>
  </a:extLst>
</a:tr>

Running the following code (when appending a new column):

prs_obj = pptx.Presentation(filepath)
tab = prs_obj.slides[0].shapes[0].table
for tr in tab._tbl.tr_lst:
    new_tc = copy.deepcopy(tr.tc_lst[-1])
    tr.append(new_tc)

Adds a new cell after the xml <a:extLst> ...</a:exLst> tag (and renders PowerPoint unable to show the cell contents). Instead I want to insert another <a:tc> element after the previous two cells, but BEFORE <a:extLst>.

All tutorials I read on xml start with premise that you have a xml file you can parse, i.e. tree = ET.parse(file), but tr.xml isn't a parseable file, it's a 'pptx.oxml.xmlchemy.XmlString' object.

scanny
  • 26,423
  • 5
  • 54
  • 80
thunt
  • 89
  • 1
  • 11

1 Answers1

1

The XML is already parsed. All you need here is:

tr.tc_lst[-1].addnext(new_tc)

instead of:

tr.append(new_tc)

This is just one of the other methods of the lxml._Element class, which all python-docx elements subclass.

scanny
  • 26,423
  • 5
  • 54
  • 80
  • THANKS! This solves it. I've upvoted (and will on the other questions too). Although at the moment my reputation < 15, so doesn't show. – thunt Nov 05 '20 at 12:13
  • You can accept the answer though (because you are the question author), that is the checkmark symbol under the up/down arrows over there on the left. Also, you get reputation points for accepting an answer to your questions. – scanny Nov 05 '20 at 18:08