Search code examples
javaapache-poipowerpointxslf

How to update a XSLFTable (table in .pptx presentation) using Apache POI?


I'm working with Apache POI and I'm trying to automate some tasks with Powerpoint reports. More precisely, I would like to update the data inside a .pptx presentation from code, including tables.

I've managed to get the XSLFTable objects (thanks to this page : How to modify the cell value of a table in an pptx file with apache-poi 3.9?), but now I'm trying to update the table structure.

Unfortunately, I don't know how to create or remove rows (or columns) in that table. The method getRows returns a list, but it seems unmodifiable. There is a addRow method, but I didn't find anything to delete/remove rows.

Do you know how I can achieve that?

Thanks a lot, and best regards!


Solution

  • Get XSLFTable

    XSLFTable t = null;
    for (XSLFShape shape : slide) {
        if (shape instanceof XSLFTable) {
            t = (XSLFTable) shape;
            r = t.getRows();
       }
    }
    

    Add Row and Cell

    XSLFTableRow titleRow = tbl.addRow();
    titleRow.setHeight(50);
    XSLFTableCell titleCell1 = titleRow.addCell();
    XSLFTextParagraph p1 = titleCell1.addNewTextParagraph();
    p1.setTextAlign(TextAlign.CENTER);
    XSLFTextRun r1 = p1.addNewTextRun();
    r1.setText("Column title");
    r1.setBold(true);
    r1.setFontColor(new Color(0, 104, 145));
    titleCell1.setFillColor(new Color(190, 230, 245));
    r1.setFontSize(25.0);
    titleCell1.setVerticalAlignment(VerticalAlignment.MIDDLE);
    

    Remove Row

    t.getCTTable().getTrList().remove(t.getNumberOfRows()-1); //Remove the last row from table.