Search code examples
javapowerpointdocx4j

Doc4j pptx find and replace table row


I have a requirement where I need to replace some text in a Powerpoint File at runtime(Powerpoint file is being used as a template with some placeholders/tokes e.g. {{data1}} ) in one row on table.

I referred to the other links on the forum and started with 'docx4j' but am not able to go beyond a point and the documentation is not very clear

    List tableCells = clonedRow.getTc();
    // Finally, insert the copy in the list
    theTable.getTr().add(clonedRow); // standard Java list API
     for (int ix = 0; ix < tableCells.size(); ix++)
     {
         CTTableCell  tableCell = (CTTableCell)XmlUtils.unwrap(tableCells.get(ix));
        // List<CTTextParagraph> value=tableCell.getTxBody().getP();

         for (CTTextParagraph p : tableCell.getTxBody().getP()) {
             Text text = (Text) ((JAXBElement) p).getValue();
            }

Solution

  • A SlidePart extends JaxbXmlPart, which contains:

    public void variableReplace(java.util.Map<String, String> mappings)
    

    If you want to use variableReplace, your variables should be appear like so: ${key1}, ${key2}

    For an example, see https://github.com/plutext/docx4j/blob/master/src/samples/docx4j/org/docx4j/samples/VariableReplace.java That's for a docx; you just need to apply it to your SlidePart.