DEV Community

Alexis
Alexis

Posted on

Java – How to Merge or Split Tables and Cells in Word Documents

When inserting tables in a Word document, you may need to merge one or more cells to create a label that spans multiple columns. Likewise, you may also need to split a cell into multiple cells to add more columns of data under a certain label. In this article, you will learn how to merge or split table cells in Word documents along with how to merge or split tables in Word documents using Java.

The following topics will be covered in this article:

Add Dependencies

To merge or split tables and cells in Word documents, this article uses Free Spire.Doc for Java. If you are using maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<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.doc.free</artifactId>
        <version>5.2.0</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

If you are not using maven, you can download the JAR file from this link, extract the zip file and then import the Spire.Doc.jar file under the lib folder into your project as a dependency.

Merge Table Cells in Word Documents using Java

You can merge two or more adjacent cells horizontally or vertically by using the Table.applyHorizontalMerge(rowIndex, startCellIndex, endCellIndex) or Table.applyVerticalMerge(columnIndex, startRowIndex, endRowIndex) methods.

The following steps show you how to merge table cells in a Word document horizontally and vertically using Java:

  • Initialize an instance of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Get the first section of the document using Document.getSections().get(sectionIndex) method.
  • Add a table to the section using Section.addTable() method.
  • Set the predefined number of rows and columns for the table using Table.resetCells(rowNum, columnNum) method.
  • Horizontally merge specific cells using Table.applyHorizontalMerge(rowIndex, startCellIndex, endCellIndex) method.
  • Vertically merge specific cells using Table.applyVerticalMerge(columnIndex, startRowIndex, endRowIndex) method.
  • Add some data to the table.
  • Save the result document using Document.saveToFile() method.
import com.spire.doc.*;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.VerticalAlignment;

public class MergeTableCells {
    public static void main(String []args) {
        //Load a Word document
        Document document = new Document();
        document.loadFromFile("Input.docx");

        //Get the first section
        Section section = document.getSections().get(0);

        //Add a 4 x 4 table to the section
        Table table = section.addTable(true);
        table.resetCells(4, 4);

        //Horizontally merge cells 1, 2, 3, and 4 in the first row
        table.applyHorizontalMerge(0, 0, 3);
        //Vertically merge cells 3 and 4 in the first column
        table.applyVerticalMerge(0, 2, 3);

        //Add some data to the table
        for(int row = 0; row < table.getRows().getCount(); row ++){
            for(int col = 0; col < table.getRows().get(row).getCells().getCount(); col++){
                TableCell cell = table.get(row, col);
                cell.getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
                Paragraph paragraph  = cell.addParagraph();
                paragraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
                paragraph.setText("Text");
            }
        }

        //Save the result document
        document.saveToFile("MergeCells.docx", FileFormat.Docx);
    }
}
Enter fullscreen mode Exit fullscreen mode

Merge table cells in Word document using Java

Split a Table Cell in Word Documents using Java

To split a table cell, you first need to access the cell using Table.getRows().get(rowIndex).getCells().get(cellIndex) method, then use TableCell.splitCell(columnNum, rowNum) method to split it into specific columns and rows.

The following steps show you how to split a table cell in a Word document using Java:

  • Initialize an instance of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Get the first section of the document using Document.getSections().get(sectionIndex) method.
  • Get the first table in the section using Section.getTables().get(tableIndex) method.
  • Get the table cell that you want to split using Table.getRows().get(rowIndex).getCells().get(cellIndex) method.
  • Split the cell into specific columns and rows using TableCell.splitCell(columnNum, rowNum) method.
  • Save the result document using Document.saveToFile() method.
import com.spire.doc.*;

public class SplitTableCells {
    public static void main(String []args) {
        //Create a Document instance
        Document document = new Document();
        document.loadFromFile("MergeCells.docx");

        Section section = document.getSections().get(0);
        Table table = section.getTables().get(0);

        //Get the cell 4 in the 4th row
        TableCell cell1 = table.getRows().get(3).getCells().get(3);
        //Split the cell into 2 columns and 2 rows
        cell1.splitCell(2, 2);

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

Split table cells in Word document using Java

Merge Tables in Word Documents using Java

Free Spire.Doc for Java allows you to merge tables by cloning rows from one table to another.

The following steps show you how to merge two tables in a Word document using Java:

  • Initialize an instance of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Get the first section of the document using Document.getSections().get(sectionIndex) method.
  • Get the first and the second tables in the section using Section.getTables().get(tableIndex) method.
  • Loop through the rows in the second table, clone each row using Table.getRows().get(rowIndex).deepClone() method. Then add the row to the first table using Table.getRows().add(TableRow) method.
  • Remove the second table from the document using Section.getTables().remove(Table) method.
  • Save the result document using Document.saveToFile() method.
import com.spire.doc.*;

public class MergeTables {
    public static void main(String []args) {
        //Load a Word document
        Document document = new Document();
        document.loadFromFile("Tables.docx");

        //Get the first section
        Section section = document.getSections().get(0);

        //Get the first and second table
        Table table1 = section.getTables().get(0);
        Table table2 = section.getTables().get(1);

        //Clone the rows of table 2 to table 1
        for (int i = 0; i < table2.getRows().getCount(); i++)
        {
            TableRow row = table2.getRows().get(i).deepClone();
            table1.getRows().add(row);
        }

        //Remove the table 2
        section.getTables().remove(table2);

        //Save the result document
        document.saveToFile("MergeTables.docx", FileFormat.Docx_2013);
    }
}
Enter fullscreen mode Exit fullscreen mode

Before:

The input Word document which contains two tables
After:

Merge tables in Word document using Java

Split a Table in Word Documents using Java

The theory to split a table is similar to that of merging tables. You need to clone specific rows from a source table to a new table, then remove these rows from the source table.

The following steps show you how to split a table into two tables in a Word document using Java:

  • Initialize an instance of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Get the first section of the document using Document.getSections().get(sectionIndex) method.
  • Get the first table in the section using Section.getTables().get(tableIndex) method.
  • Initialize an instance of Table class to create a new table.
  • Clone specific rows of the first table using Table.getRows().get(rowIndex).deepClone() method, then add it to the new table using Table.getRows().add(TableRow) method.
  • Remove the specific rows from the first table using Table.getRows().removeAt(rowIndex) method.
  • Add the new table to the first section using Section.getTables().add(Table) method.
  • Save the result document using Document.saveToFile() method.
import com.spire.doc.*;

public class SplitTables {
    public static void main(String []args) {
        //Load a Word document
        Document document = new Document();
        document.loadFromFile("MergeTables.docx");

        //Get the first section
        Section section = document.getSections().get(0);

        //Get the first table
        Table table = section.getTables().get(0);

        //Create a new table for the splitted rows
        Table newTable = new Table(document);

        //Specify the row index to start the splitting;
        int splitIndex = 3;

        //Clone specific rows from the first table to the new table
        for (int i = splitIndex; i < table.getRows().getCount(); i++)
        {
            TableRow row = table.getRows().get(i).deepClone();
            newTable.getRows().add(row);
        }

        //Remove the specific rows from the first table
        for (int i = table.getRows().getCount() - 1; i >= splitIndex; i--)
        {
            table.getRows().removeAt(i);
        }

        //Add the new table in section
        section.getTables().add(newTable);

        //Save the result document
        document.saveToFile("SplitTables.docx", FileFormat.Docx_2013);
    }
}
Enter fullscreen mode Exit fullscreen mode

Split a table in Word document using Java

Top comments (0)