DEV Community

loading...

Java/ Merge and Split Table Cells In Word

jazzzzz profile image Jane ・2 min read

I've introduced how to create a table in Word document using Free Spire.Doc for Java, and this article will share how to use this free Java API to merge and split table cells in Word document.

1# Installation
Method 1: Download the Free Spire.Doc for Java and unzip it, then add the Spire.Doc.jar file to your project as dependency.

Method 2: You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
   <repository>
      <id>com.e-iceblue</id>
      <name>e-iceblue</name>
      <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
   </repository>
</repositories>
<dependencies>
   <dependency>
      <groupId>e-iceblue</groupId>
      <artifactId>spire.doc.free</artifactId>
      <version>3.9.0</version>
   </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

2# Example of merging cells:

import com.spire.doc.*;

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

        String output = "out/MergeTableCells.docx";

        //Create a Document instance
        Document document = new Document();

        //Add a table to it
        Section section = document.addSection();
        Table table = section.addTable(true);
        table.resetCells(4, 4);

        //Merge cells horizontally
        table.applyHorizontalMerge(0, 0, 3);

        //Merge cells vertically
        table.applyVerticalMerge(0, 2, 3);

        //save the document to file
        document.saveToFile(output, FileFormat.Docx);
    }
}
Enter fullscreen mode Exit fullscreen mode

Alt Text

3# Example of spliting cells:

import com.spire.doc.*;

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

        String output = "out/SplitTableCells.docx";

        //Create a Document instance
        Document document = new Document();

        //Add a table to it
        Section section = document.addSection();
        Table table = section.addTable(true);
        table.resetCells(4, 4);

        //split the cell
        table.getRows().get(3).getCells().get(3).splitCell(2, 2);

        //save the document to file
        document.saveToFile(output, FileFormat.Docx);
    }
}
Enter fullscreen mode Exit fullscreen mode

Alt Text

Discussion (0)

Forem Open with the Forem app