Spire.Doc offers Table.applyVerticalMerge() method to merge table cells vertically and Table.applyHorizontalMerge() method to merge table cells horizontally. By default, the merged cells will have repeated values if the cells to be merged contain the same value. This article will demonstrate how to remove repeated values in the merged cells using a customized method with Spire.Doc for Java.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use 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</artifactId>
        <version>12.4.6</version>
    </dependency>
</dependencies>
    

Remove Duplicate Values When Merging Cells

The following are the steps to remove the duplicate values in the merged cells in a Word table.

  • Create an object of Document class and load the sample document using Document.loadFromFile() method.
  • Use Document.getSections() method to get the section collection, and then get the specific section using SectionCollection.get() method.
  • Use Section.getTables() method to get the table collection, and then get the desired table using TableCollection.get() method
  • Invoke mergeCell(Table table, boolean isHorizontalMerge, int index, int start, int end) method to merge table cells vertically or horizontally. This method will determine whether the cells to be merged have the same value, and will preserve only one value in the merged cell.
  • Save the document to file using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.interfaces.ITable;

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

        //Create an object of Document class and load the sample document.
        Document document = new Document();
        document.loadFromFile("Sample.docx");

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

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

        //Invoike mergeCell()method to merge cells vertically
        mergeCell(table, false, 0, 1, 3);

        //Invoike mergeCell()method to merge cell horizontally
        mergeCell(table, true, 0, 4, 5);

        //Save the document to file
        document.saveToFile("MergeTable.docx",FileFormat.Docx_2013);
}

        //Customize a mergeCell() method to remove the duplicate values while merging cells
        public static void mergeCell(Table table, boolean isHorizontalMerge, int index, int start, int end) {
        
        if (isHorizontalMerge) {
            //Get a cell from table
            TableCell firstCell = table.get(index, start);
            //Invoke getCellText() method to get the cell’s text
            String firstCellText = getCellText(firstCell);
            for (int i = start + 1; i <= end; i++) {
                TableCell cell1 = table.get(index, i);
                //Check if the text is the same as the first cell                
        if (firstCellText.equals(getCellText(cell1))) {
                    //If yes, clear all the paragraphs in the cell
                    cell1.getParagraphs().clear();
                }
            }
            //Merge cells horizontally
            table.applyHorizontalMerge(index, start, end);

        } 
            else {
            TableCell firstCell = table.get(start, index);
            String firstCellText = getCellText(firstCell);
            for (int i = start + 1; i <= end; i++) {
                TableCell cell1 = table.get(i, index);
                if (firstCellText.equals(getCellText(cell1))) {
                    cell1.getParagraphs().clear();
                }
            }
            //Merge cells vertically
            table.applyVerticalMerge(index, start, end);
        }
    }
        public static String getCellText(TableCell cell) {

        StringBuilder text = new StringBuilder();
        //Traverse all the paragraphs of a cell
        for (int i = 0; i < cell.getParagraphs().getCount(); i++) {
            //Get every paragraph’s text and append it to StringBuilder
            text.append(cell.getParagraphs().get(i).getText().trim());
        }
        return text.toString();
    }
}

Java: Remove Duplicate Values When Merging Cells in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Table

This article demonstrates how to align a table in a Word document using Spire.Doc for Java.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Table;
import com.spire.doc.documents.RowAlignment;

public class AlignTable {

    public static void main(String[] args) {

        //Create a Document object
        Document doc=new Document();

        //Add a table
        Table table =doc.addSection().addTable(true);

        //Set column width
        table.setColumnWidth(new float[]{100f,150f});

        //Set column number and row number
        table.resetCells(2,2);

        //Add text to cells
        table.get(0,0).addParagraph().appendText("Product Code");
        table.get(0,1).addParagraph().appendText("Description");
        table.get(1,0).addParagraph().appendText("T1052");
        table.get(1,1).addParagraph().appendText("AdvoCareSlim Tropical Swirl");

        //Align table to center
        table.getTableFormat().setHorizontalAlignment(RowAlignment.Center);

        //Save the document
        doc.saveToFile("AlignTable.docx", FileFormat.Docx_2013);
    }
}

Align a Table Horizontally in Word in Java

Published in Table
Friday, 24 July 2020 05:43

How to Autofit a Word Table in Java

This article demonstrates how to auto fit a Word table to content or to window, as well as how to fix the cloumn widths, by using Spire.Doc for Java.

Autofit to content

import com.spire.doc.*;

public class AutofitToContent {
    public static void main(String[] args) {

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

        //Add a section
        Section section = document.addSection();

        //Add a table
        Table table = section.addTable();
        table.resetCells(3, 2);

        //Add content to the cells
        table.get(0,0).addParagraph().appendText("Product Code");
        table.get(0,1).addParagraph().appendText("Description");
        table.get(1,0).addParagraph().appendText("T1052");
        table.get(1,1).addParagraph().appendText("AdvoCareSlim Tropical Swirl");
        table.get(2,0).addParagraph().appendText("T1062");
        table.get(2,1).addParagraph().appendText("AdvoCareSlim Caffeine Free Strawberry Kiwi");

        //Autofit column widths to contents
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);

        //Save the document
        document.saveToFile("AutofitToContent.docx", FileFormat.Docx);
    }
}

How to Autofit a Word Table in Java

Autofit to window

import com.spire.doc.*;

public class AutofitToWindow {

    public static void main(String[] args) {

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

        //Add a section
        Section section = document.addSection();

        //Add a table
        Table table = section.addTable();
        table.resetCells(3, 2);

        //Add content to the cells
        table.get(0,0).addParagraph().appendText("Product Code");
        table.get(0,1).addParagraph().appendText("Description");
        table.get(1,0).addParagraph().appendText("T1052");
        table.get(1,1).addParagraph().appendText("AdvoCareSlim Tropical Swirl");
        table.get(2,0).addParagraph().appendText("T1062");
        table.get(2,1).addParagraph().appendText("AdvoCareSlim Caffeine Free Strawberry Kiwi");

        //Autofit column widths to window
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window);

        //Save the document
        document.saveToFile("AutofitToWindow.docx", FileFormat.Docx);
    }
}

How to Autofit a Word Table in Java

Fix column width

import com.spire.doc.*;

public class FixColumnWidths {
    public static void main(String[] args) {

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

        //Add a section
        Section section = document.addSection();

        //Add a table
        Table table = section.addTable();
        table.resetCells(3, 2);

        //Add content to the cells
        table.get(0, 0).addParagraph().appendText("Product Code");
        table.get(0, 1).addParagraph().appendText("Description");
        table.get(1, 0).addParagraph().appendText("T1052");
        table.get(1, 1).addParagraph().appendText("AdvoCareSlim Tropical Swirl");
        table.get(2, 0).addParagraph().appendText("T1062");
        table.get(2, 1).addParagraph().appendText("AdvoCareSlim Caffeine Free Strawberry Kiwi");

        //Set the column widths
        for (int i = 0; i < table.getRows().getCount(); i++) {

            table.get(i,0).setCellWidth(80f,CellWidthType.Point);
            table.get(i,1).setCellWidth(160f,CellWidthType.Point);
        }

        //Fix the column widths so that the column width does not increases when the content exceeds the width
        table.autoFit(AutoFitBehaviorType.Fixed_Column_Widths);

        //Save the document
        document.saveToFile("FixColumnWidths.docx", FileFormat.Docx);
    }
}

How to Autofit a Word Table in Java

Published in Table

This article demonstrates how to insert images to table cells in a Word document using Spire.Doc for Java.

import com.spire.doc.AutoFitBehaviorType;
import com.spire.doc.Document;
import com.spire.doc.Section;
import com.spire.doc.Table;
import com.spire.doc.fields.DocPicture;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class InsertImageToTableCell {

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

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

        //Add a section
        Section section  = document.addSection();

        //Add a table
        Table table = section.addTable(true);
        table.resetCells(2,2);
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);

        //Load an image to InputStream
        InputStream inputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\company-logo.png");
        
        //Insert the image to the cell(0,0)
        DocPicture picture = table.get(0,0).addParagraph().appendPicture(inputStream);
        
        //Set the width and height of the image
        picture.setWidth(100);
        picture.setHeight(100);

        //Insert another image to the cell(1,1)
        inputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\intro.png");
        picture = table.get(1,1).addParagraph().appendPicture(inputStream);
        picture.setWidth(100);
        picture.setHeight(100);

        //Save the document
        document.saveToFile("InsertImgToCell.docx");
    }
}

Insert Images to a Table in Word in Java

Published in Table
Thursday, 02 July 2020 08:54

Create a Nested Table in Word in Java

This article demonstrates how to insert a nested table in a table cell using Spire.Doc for Java.

import com.spire.doc.*;

public class CreateNestedTable {
    public static void main(String[] args) {

        //Create a Document object
        Document doc = new Document();
        
        //Add a section
        Section section = doc.addSection();

        //Add a table
        Table table = section.addTable(true);
        table.resetCells(2, 3);

        //Set column width
        table.getRows().get(0).getCells().get(0).setWidth(50f);
        table.getRows().get(0).getCells().get(2).setWidth(50f);
        table.getRows().get(1).getCells().get(0).setWidth(50f);
        table.getRows().get(1).getCells().get(2).setWidth(50f);
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window);

        //Insert content to cells
        table.get(0,0).addParagraph().appendText("SI.No.");
        String text = "Earthwork excavation for foundation of buildings, water supply, "
                + "sanitary lines and electrical conduits either in pits or in "
                + "trenches 1.5m and above in width, in ordinary soil not exceeding "
                + "1.5m in depth including dressing the bottom and sides of pits and  "
                + "trenches, stacking the excavated soil clear.";
        table.get(0,1).addParagraph().appendText(text);
        table.get(0,2).addParagraph().appendText("Qty");

        //Add a nested table to cell(0,1)
        Table nestedTable = table.get(0,1).addTable();
        nestedTable.resetCells(3, 4);
        nestedTable.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);

        //Add content to the cells of nested table
        nestedTable.get(0,0).addParagraph().appendText("SI.No.");
        nestedTable.get(0,1).addParagraph().appendText("Item");
        nestedTable.get(0,2).addParagraph().appendText("Qty");
        nestedTable.get(0,3).addParagraph().appendText("Rate");
        nestedTable.get(1,0).addParagraph().appendText("1");
        nestedTable.get(1,1).addParagraph().appendText("Sand");
        nestedTable.get(1,2).addParagraph().appendText("30");
        nestedTable.get(1,3).addParagraph().appendText("45");
        nestedTable.get(2,0).addParagraph().appendText("2");
        nestedTable.get(2,1).addParagraph().appendText("Cement");
        nestedTable.get(2,2).addParagraph().appendText("30");
        nestedTable.get(2,3).addParagraph().appendText("50");

        //Save the document
        doc.saveToFile("NestedTable.docx", FileFormat.Docx_2013);
    }
}

Create a Nested Table in Word in Java

Published in Table

In this article, we will introduce how to set style and border of a Word table using Spire.Doc for Java.

The following screenshot shows the table before setting style and border:

Set Style and Border of Table in Word in Java

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.Table;
import com.spire.doc.documents.BorderStyle;
import com.spire.doc.documents.DefaultTableStyle;

import java.awt.*;

public class SetTableStyleAndBorder {
    public static void main(String[] args){
        //create a Document instance
        Document document = new Document();
        //Load the Word document
        document.loadFromFile("tableSample.docx");

        Section section = document.getSections().get(0);

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

        //apply the table style
        table.applyStyle(DefaultTableStyle.Colorful_List);

        //set right border of table
        table.getTableFormat().getBorders().getRight().setBorderType(BorderStyle.Hairline);
        table.getTableFormat().getBorders().getRight().setLineWidth(1.0F);
        table.getTableFormat().getBorders().getRight().setColor(Color.RED);

        //set top border of table
        table.getTableFormat().getBorders().getTop().setBorderType(BorderStyle.Hairline);
        table.getTableFormat().getBorders().getTop().setLineWidth(1.0F);
        table.getTableFormat().getBorders().getTop().setColor(Color.GREEN);

        //set left border of table
        table.getTableFormat().getBorders().getLeft().setBorderType(BorderStyle.Hairline);
        table.getTableFormat().getBorders().getLeft().setLineWidth(1.0F);
        table.getTableFormat().getBorders().getLeft().setColor(Color.YELLOW);

        //set bottom border of table
        table.getTableFormat().getBorders().getBottom().setBorderType(BorderStyle.Dot_Dash);

        //set vertical and horizontal border
        table.getTableFormat().getBorders().getVertical().setBorderType(BorderStyle.Dot);
        table.getTableFormat().getBorders().getHorizontal().setBorderType(BorderStyle.None);
        table.getTableFormat().getBorders().getVertical().setColor(Color.ORANGE);

        //save the result file
        document.saveToFile("setTableStyleAndBorder.docx", FileFormat.Docx_2013);
    }
}

The following screenshot shows the table after setting style and border:

Set Style and Border of Table in Word in Java

Published in Table
Thursday, 29 June 2023 07:44

Java: Merge or Split Table Cells in Word

Tables in Word are a useful feature for organizing and presenting data. While the default table has an equal number of cells in each column or row, there are times when you may need to combine multiple cells to create a header, or split a cell to accommodate additional data. This article will introduce how to programmatically merge or split cells in a Word table using Spire.Doc for Java.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use 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</artifactId>
        <version>12.4.6</version>
    </dependency>
</dependencies>
    

Merge Table Cells in Word in Java

With Spire.Doc for .NET, you can merge two or more adjacent cells horizontally or vertically using the Table.applyHorizontalMerge() or Table.applyVerticalMerge() method. The following are the detailed steps.

  • Create a Document instance.
  • Load a Word document using Document.loadFromFile() method.
  • Get a specified section in the document using Document.getSections().get() method.
  • Add a table to the section using Section.addTable() method.
  • Specify the number of rows and columns of the table using Table.resetCells(int rowsNum, int columnsNum) method.
  • Horizontally merge specified cells in the table using Table.applyHorizontalMerge(int rowIndex, int startCellIndex, int endCellIndex) method.
  • Vertically merge specified cells in the table using Table.applyVerticalMerge(int columnIndex, int startRowIndex, int endRowIndex) method.
  • Add some data to the table.
  • Save the result document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.VerticalAlignment;

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

        //Create a Document instance
        Document document = new Document();
        
        //Load a sample Word 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("MergeTableCells.docx", FileFormat.Docx);
    }
}

Java: Merge or Split Table Cells in Word

Split Table Cells in Word in Java

To divide a cell in a Word table into multiple cells, Spire.Doc for .NET offers the TableCell.splitCell(int columnNum, int rowNum) method. The following are the detailed steps.

  • Create a Document instance.
  • Load a Word document using Document.loadFromFile() method.
  • Get a specified section in the document using Document.getSections().get() method.
  • Get a specified table in the section using Section.getTables().get() method.
  • Get the table cell that need to be split using Table.getRows().get().getCells().get() method.
  • Split the cell into specific number of columns and rows using TableCell.splitCell(int columnNum, int rowNum) method.
  • Save the result document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;

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

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

        //Load a sample Word document
        document.loadFromFile("MergeTableCells.docx");

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

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

        //Get the 4th cell 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 result document
        document.saveToFile("SplitTableCells.docx", FileFormat.Docx);
    }
}

Java: Merge or Split Table Cells in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Table
Friday, 24 May 2019 09:25

Java: Create a Table in Word

A table is a common way to present tabular data in a Word document. It helps a lot in organizing a big set of information. In this article, you'll learn how to create how to create a table, fill the table with data, and apply formatting to the table cells using Spire.Doc for Java.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use 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</artifactId>
        <version>12.4.6</version>
    </dependency>
</dependencies>
    

Create a Simple Table in Word

The table below lists some of the core classes and methods responsible for creating as well as formatting a table.

Name Description
Table Class Represents a table in a Word document.
TableRow Class Represents a row in a table.
TableCell Class Represents a specific cell in a table.
Section.addTbale() Method Adds a new table to the specified section.
Table.resetCells() Method Resets row number and column number.
Table.getRows() Method Gets the table rows.
TableRow.setHeight() Method Sets the height of the specified row.
TableRow.getCells() Method Returns the cells collection.
TableRow.getFormat() Method Gets the format of the specified row.

The following are the steps to create a simple table in a Word document.

  • Create a Document object, and add a section to it.
  • Prepare the data for the header row and other rows, storing them in a one-dimensional string array and a two-dimensional string array respectively.
  • Add a table to the section using Section.addTable() method.
  • Insert data to the header row, and set the row formatting, including row height, background color, and text alignment.
  • Insert data to the rest of the rows, and apply formatting to these rows.
  • Save the document to another file using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class CreateTable {

    public static void main(String[] args) {

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

        //Add a section
        Section section = document.addSection();

        //Define the data for table
        String[] header = {"Name", "Capital", "Continent", "Area", "Population"};
        String[][] data =
                {
                        new String[]{"Argentina", "Buenos Aires", "South America", "2777815", "32300003"},
                        new String[]{"Bolivia", "La Paz", "South America", "1098575", "7300000"},
                        new String[]{"Brazil", "Brasilia", "South America", "8511196", "150400000"},
                        new String[]{"Canada", "Ottawa", "North America", "9976147", "26500000"},
                        new String[]{"Chile", "Santiago", "South America", "756943", "13200000"},
                        new String[]{"Colombia", "Bogota", "South America", "1138907", "33000000"},
                        new String[]{"Cuba", "Havana", "North America", "114524", "10600000"},
                        new String[]{"Ecuador", "Quito", "South America", "455502", "10600000"},
                        new String[]{"El Salvador", "San Salvador", "North America", "20865", "5300000"},
                        new String[]{"Guyana", "Georgetown", "South America", "214969", "800000"},

                };

        //Add a table
        Table table = section.addTable(true);
        table.resetCells(data.length + 1, header.length);

        //Set the first row as table header
        TableRow row = table.getRows().get(0);
        row.isHeader(true);
        row.setHeight(20);
        row.setHeightType(TableRowHeightType.Exactly);
        row.getRowFormat().setBackColor(Color.gray);
        for (int i = 0; i < header.length; i++) {
            row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
            Paragraph p = row.getCells().get(i).addParagraph();
            p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
            TextRange txtRange = p.appendText(header[i]);
            txtRange.getCharacterFormat().setBold(true);
        }

        //Add data to the rest of rows
        for (int r = 0; r < data.length; r++) {
            TableRow dataRow = table.getRows().get(r + 1);
            dataRow.setHeight(25);
            dataRow.setHeightType(TableRowHeightType.Exactly);
            dataRow.getRowFormat().setBackColor(Color.white);
            for (int c = 0; c < data[r].length; c++) {
                dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
                dataRow.getCells().get(c).addParagraph().appendText(data[r][c]);
            }
        }

        //Set background color for cells
        for (int j = 1; j < table.getRows().getCount(); j++) {
            if (j % 2 == 0) {
                TableRow row2 = table.getRows().get(j);
                for (int f = 0; f < row2.getCells().getCount(); f++) {
                    row2.getCells().get(f).getCellFormat().setBackColor(new Color(173, 216, 230));
                }
            }
        }

        //Save to file
        document.saveToFile("output/CreateTable.docx", FileFormat.Docx_2013);
    }
}

Java: Create a Table in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Table