Merge and Split Table Cells in PowerPoint in Java

·

2 min read

Tables in PowerPoint can display data in a more organized way. When you creating a table in a presentation slide, sometimes you may need to merge or split specified cells. This article will share how to merge and split the cells using Free Spire.Presentation for Java.

Import Dependency (2 Methods)

  • Download the free API and unzip it, and then add the Spire.Presentation.jar file to your project as dependency.

  • Directly add the jar dependency to your maven project by adding the following configurations to the pom.xml.

    <repositories>
      <repository>
          <id>com.e-iceblue</id>
          <name>e-iceblue</name>
          <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
      </repository>
    </repositories>
    <dependencies>
      <dependency>
          <groupId>e-iceblue</groupId>
          <artifactId>spire.presentation.free</artifactId>
          <version>5.1.0</version>
      </dependency>
    </dependencies>
    

Sample Code

Free Spire.Presentation for Java offers the ITable.mergeCells(Cell cell1, Cell cell2, boolean allowSplitting) method to merge the specified cells. To split a cell, you can use the ITable.get(int columnIndex, int rowIndex).split(int RowCount, int ColunmCount) method. The complete sample code is shown as below:

import com.spire.presentation.FileFormat;
import com.spire.presentation.ITable;
import com.spire.presentation.Presentation;

public class MergeAndSplitCells {

    public static void main(String[] args) throws Exception {

        //create a Presentation object
        Presentation presentation = new Presentation();

        //load a sample PowerPoint file
        presentation.loadFromFile("E:/Files/table.pptx");

        //declare ITable variable
        ITable table = null;

        //get the table from the presentation slide
        for (Object shape : presentation.getSlides().get(0).getShapes()) {
            if (shape instanceof ITable) {
                table = (ITable) shape;

                //merge the cells between cell[2,0] and cell[3,0]
                table.mergeCells(table.get(2, 0), table.get(3, 0), false);

                //merge the cells between  cell[0,1] and cell[0,2]
                table.mergeCells(table.get(0, 1), table.get(0, 2), false);

                //merge the cells between  cell[0,3] and cell[0,5]
                table.mergeCells(table.get(0, 3), table.get(0, 5), false);

                //split cell[2,3] to 2 columns
                table.get(4,5).split(1,2);
            }
        }

        //save to file
        presentation.saveToFile("MergeAndSplitCells.pptx", FileFormat.PPTX_2010);
    }
}

MergeCell.jpeg