Java: Create a Table in Word

2019-05-24 09:25:50 Written by Koohji

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>13.11.2</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);
        for (int j = 0; j < row.getCells().getCount(); j++) {
            row.getCells().get(j).getCellFormat().getShading().setBackgroundPatternColor(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);
            for (int c = 0; c < dataRow.getCells().getCount(); c++) {
                dataRow.getCells().get(c).getCellFormat().getShading().setBackgroundPatternColor(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().getShading().setBackgroundPatternColor(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.

Java: Add or Remove Bookmarks in Word

2022-03-03 07:49:00 Written by Koohji

Bookmarks in Microsoft Word can mark text, pictures, and places in a document, allowing you to jump straight to the desired text, picture, or place without scrolling through several paragraphs or pages. This is especially useful for navigating some research papers or contracts that contain a lot of pages. In this article, you will learn how to programmatically add or remove a bookmark in a Word document 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>13.11.2</version>
    </dependency>
</dependencies>

Add a Bookmarks to an Existing Word Document

The detailed steps are as follows:

  • Create a Document instance.
  • Load a sample Word document using Document.loadFromFile() method.
  • Get the first section using Document.getSections().get() method.
  • Get a specified paragraph using Section.getParagraphs().get() method.
  • Append the start of the bookmark with specified name to the specified paragraph using Paragraph.appendBookmarkStart(java.lang.String name) method.
  • Append the end of the bookmark with specified name to the specified paragraph using Paragraph.appendBookmarkEnd(java.lang.String name) method.
  • Save the document to another file using Document. saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;

public class InsertBookmark {

    public static void main(String[] args) {

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

        //Load a sample Word file
        doc.loadFromFile("sample.docx");

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

        //Insert a bookmark with specified name into the specified paragraphs
        section.getParagraphs().get(7).appendBookmarkStart("ConversionFunction");
        section.getParagraphs().get(16).appendBookmarkEnd("ConversionFunction");


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

Java: Add or Remove Bookmarks in Word

Remove an Existing Bookmark in a Word Document

The detailed steps are as follows:

  • Create a Document instance.
  • Load a sample Word document using Document.loadFromFile() method.
  • Get a specified bookmark by its index using Document.getBookmarks().get() method.
  • Remove the specified bookmark using Document.getBookmarks().remove() method.
  • Save the document to another file using Document.saveToFile() method.
  • Java
import com.spire.doc.Bookmark;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class RemoveBookmark {

    public static void main(String[] args) {

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

        //Load a sample Word file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\AddBookmark.docx");

        //Get bookmark by its index
        Bookmark bookmark = doc.getBookmarks().get(0);

        //Remove the bookmark
        doc.getBookmarks().remove(bookmark);

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

Java: Add or Remove Bookmarks 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.

Java: Set Paragraph Indents in Word

2019-05-21 08:53:40 Written by Koohji

In Microsoft Word, we can set the paragraph indents as left, right, first line or hanging. In this article, we will demonstrate how to achieve this functionality 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>13.11.2</version>
    </dependency>
</dependencies>

Set Paragraph Indents in Word

Spire.Doc for Java provides a ParagraphFormat class to work with paragraph formatting. You can use Paragraph.getFormat() method to get the ParagraphFormat object, and then use the following methods to set the corresponding paragraph indents with the object:

Indents Methods Descriptions
Left ParagraphFormat.setLeftIndent(float value) Indents the paragraph on the left by the amount you set.
Right ParagraphFormat.setRightIndent(float value) Indents the paragraph on the right by the amount you set.
First line ParagraphFormat.setFirstLineIndent(float value) Indent the first line of a paragraph.
Hanging ParagraphFormat.setFirstLineIndent(float negativeValue) Sets off the first line of a paragraph by positioning it at the margin, and then indenting each subsequent line of the paragraph.

The following are the steps to set paragraph indents:

  • Create a Document instance.
  • Load a Word document using Document.loadFromFile() method.
  • Get the desired section by its index using Document.getSections.get() method.
  • Get the desired paragraph by index using Section.getParagraphs.get() method.
  • Get the ParagraphFormat object using Paragraph.getFormat() method.
  • Call the methods listed in above table to set paragraph indents with the object.
  • Save the result document using Document.saveToFile() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.formatting.ParagraphFormat;

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

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

        //Get the second paragraph and set left indent
        Paragraph para = section.getParagraphs().get(1);
        ParagraphFormat format = para.getFormat();
        format.setLeftIndent(30);

        //Get the third paragraph and set right indent
        para = section.getParagraphs().get(2);
        format = para.getFormat();
        format.setRightIndent(30);

        //Get the fourth paragraph and set first line indent
        para = section.getParagraphs().get(3);
        format = para.getFormat();
        format.setFirstLineIndent(30);

        //Get the fifth paragraph and set hanging indent
        para = section.getParagraphs().get(4);
        format = para.getFormat();
        format.setFirstLineIndent(-30);

        //Save the result document
        document.saveToFile("SetParagraphIndents.docx", FileFormat.Docx_2013);
    }
}

The following is the output Word document after setting paragraph indents:

Java: Set Paragraph Indents 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.

page 67