How to Format the Text in a Word Document using Java?
Last Updated :
17 Jan, 2022
Apache POI is a project run by the Apache Software Foundation, and previously a sub-project of the Jakarta Project provides pure Java libraries for reading and writing files in Microsoft Office formats, such as Word, PowerPoint, and Excel. First do install Apache in order to import modules as per the guide for the ecosystem based on operating systems such as Windows/Linux Systems. In order to format the text in a Word document using java, the basic requirement in importing libraries is Apache POI.
Approach:
- Create an empty Document Object using XWPFDocument from Apache POI package.
- Create a FileOutputStream Object to save the Word Document in the desired path/location in the system.
- Create a Paragraph using XWPFParagraph Object in the document.
- Create Lines of Text using XWPFRun Object and apply formatting attributes.
Implementation:
- Creating a blank document.
- Getting path of current working directory to create the PDF file in the same directory.
- Creating a file object with the path specified above.
- Create paragraph using createParagraph() method.
- Formatting of lines.
- Saving changes to document.
- Closing the connections.
Sample input Image:
Example
Java
import java.io.*;
import org.apache.poi.xwpf.usermodel.*;
public class GFG {
public static void main(String[] args) throws Exception
{
XWPFDocument document = new XWPFDocument();
String path = System.getProperty( "user.dir" );
path += "/FormattedWord.docx" ;
FileOutputStream out
= new FileOutputStream( new File(path));
XWPFParagraph paragraph
= document.createParagraph();
XWPFRun line1 = paragraph.createRun();
line1.setBold( true );
line1.setText( "Formatted with Bold" );
line1.addBreak();
XWPFRun line2 = paragraph.createRun();
line2.setText( "Formatted with Italics" );
line2.setItalic( true );
line2.addBreak();
XWPFRun line3 = paragraph.createRun();
line3.setColor( "73fc03" );
line3.setFontSize( 20 );
line3.setText( " Formatted with Color" );
document.write(out);
out.close();
document.close();
System.out.println(
"Word Document with Formatted Text created successfully!" );
}
}
|
Output: changes made as per above program in the sample input image illustrated.
Output
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...