Java: Edit a Word Document

Editing a Word document is a common task that many people encounter in their daily lives, whether it's for work, school, or personal projects. From correcting spelling and grammar errors to rearranging content and formatting the document, the ability to edit a Word document efficiently is a valuable skill.

In this article, you will learn how to programmatically edit or modify 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>12.11.0</version>
    </dependency>
</dependencies>
    

Modify Text in a Word Document in Java

To retrieve the paragraph from a particular section, you can use the Section.getParagraphs().get() method. Once you have the target paragraph, you can then update its text content by calling the Paragraph.setText() method and passing in the new text you want to assign.

The following are the steps modify text in a Word document using Java:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Get a specific section using Document.getSections().get() method.
  • Get a specific paragraph using Section.getParagraphs().get() method.
  • Reset the text of the paragraph using Paragraph.setText() method.
  • Save the updated document to a different Word file.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;

public class ModifyText {
https://ok.166.net/reunionpub/2023-06-06/ntesgod_cms/1686032662375_vfdeuv.png
    public static void main(String[] args) {

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

        // Load an existing Word file
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

        // Get a specific section
        Section section = document.getSections().get(0);

        // Get a specific paragraph
        Paragraph paragraph = section.getParagraphs().get(0);

        // Modify the text of the paragraph
        paragraph.setText("The title has been modified");

        // Save the document to a different Word file
        document.saveToFile("ModifyText.docx", FileFormat.Docx);

        // Dispose resource
        document.dispose();
    }
}

Java: Edit a Word Document

Change Formatting of Text in a Word Document in Java

To modify the formatting of specific text within a paragraph, you first need to access the target paragraph object. Once you have the paragraph, you can then iterate through its child elements to locate the individual text ranges.

For each text range found, you can update the formatting by using the methods under the CharacterFormat object. This allows you to set properties like font name, size, color, and other text-level formatting options for the selected text.

The steps to change text formatting in a Word document are as follows:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Get a specific section using Document.getSections().get() method.
  • Get a specific paragraph using Section.getParagraphs().get() method.
  • Iterate through the child objects in the paragraph.
    • Determine if a child object is a text range.
    • Get a specific text range.
    • Reset the text formatting using the methods under the CharacterFormat object.
  • Save the updated document to a different Word file.
  • 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.fields.TextRange;

import java.awt.*;

public class ChangeTextFormatting {

    public static void main(String[] args) {

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

        // Load an existing Word file
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

        // Get a specific section
        Section section = document.getSections().get(0);

        // Get a specific paragraph
        Paragraph paragraph = section.getParagraphs().get(1);

        // Iterate through the child objects in the paragraph
        for (int i = 0; i < paragraph.getChildObjects().getCount(); i++)
        {
            // Determine if a child object is text range
            if (paragraph.getChildObjects().get(i) instanceof TextRange)
            {
                // Get a specific text range
                TextRange textRange = (TextRange)paragraph.getChildObjects().get(i);

                // Reset font name for it
                textRange.getCharacterFormat().setFontName("Corbel Light");

                // Reset font size for it
                textRange.getCharacterFormat().setFontSize(11);

                // Reset text color for it
                textRange.getCharacterFormat().setTextColor(Color.blue);

                // Apply italic to the text range
                textRange.getCharacterFormat().setItalic(true);
            }
        }

        // Save the document to a different Word file
        document.saveToFile("ChangeFont.docx", FileFormat.Docx);

        // Dispose resource
        document.dispose();
    }
}

Java: Edit a Word Document

Add New Elements to a Word Document in Java

When working with Word documents, the paragraph serves as the foundational unit for incorporating diverse elements like text, images, lists, and charts. To introduce a new paragraph within a specific section, you can leverage the Section.addParagraph() method.

Once the paragraph has been added, you can then proceed to add various other elements to it by utilizing the methods available within the Paragraph object.

The following are the steps to add new elements (text and images) to a Word document using Java:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Get a specific section using Document.getSections() method.
  • Add a paragraph to the section using Section.addParagraph() method.
  • Add text to the paragraph using Paragraph.appendText() method.
  • Add an image to the paragraph using Paragraph.appendPicture() method.
  • Save the updated document to a different Word file.
  • 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.documents.ParagraphStyle;

public class AddNewElements {

    public static void main(String[] args) {

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

        // Load an existing Word file
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

        // Get the last section
        Section lastSection = document.getLastSection();

        // Add a paragraph to the section
        Paragraph paragraph = lastSection.addParagraph();

        // Add text to the paragraph
        paragraph.appendText("This text and the image shown below are added programmatically using Spire.Doc for Java.");

        // Add an image to the paragraph
        paragraph.appendPicture("C:\\Users\\Administrator\\Desktop\\logo.png");

        // Create a paragraph style
        ParagraphStyle style = new ParagraphStyle(document);
        style.setName("FontStyle");
        style.getCharacterFormat().setFontName("Times New Roman");
        style.getCharacterFormat().setFontSize(12);
        document.getStyles().add(style);

        // Apply the style to the paragraph
        paragraph.applyStyle(style.getName());

        // Save the document to a different Word file
        document.saveToFile("AddNewElements.docx", FileFormat.Docx);

        // Dispose resource
        document.dispose();
    }
}

Java: Edit a Word Document

Remove Paragraphs from a Word Document in Java

To remove a specific paragraph from the collection of paragraphs within a document, you can call the ParagraphCollection.removeAt() method. This method takes the index of the paragraph you wish to remove as an argument, allowing you to selectively delete the desired paragraph from the document.

The steps to remove paragraphs from a Word document using Java are as follows:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Get a specific section using Document.getSections().get() method.
  • Remove a specific paragraph from the section using ParagraphCollection.removeAt() method.
  • Save the updated document to a different Word file.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;

public class RemoveParagraph {

    public static void main(String[] args) {

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

        // Load an existing Word file
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

        // Get a specific section
        Section section = document.getSections().get(0);

        // Remove a specific paragraph
        section.getParagraphs().removeAt(0);

        // Save the document to a different Word file
        document.saveToFile("RemoveParagraph.docx", FileFormat.Docx);

        // Dispose resource
        document.dispose();
    }
}

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.