Monday, May 30, 2022

How to create MS Word file using Java

Use Maven to add dependency:


  <dependency>

<groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency>


public class CreateDocumentSimple { public static void main(String[] args) throws IOException { String fileName = "c:\\test\\hello.docx"; try (XWPFDocument doc = new XWPFDocument()) { // create a paragraph XWPFParagraph p1 = doc.createParagraph(); p1.setAlignment(ParagraphAlignment.CENTER); // set font XWPFRun r1 = p1.createRun(); r1.setBold(true); r1.setItalic(true); r1.setFontSize(22); r1.setFontFamily("New Roman"); r1.setText("I am first paragraph."); // save it to .docx file try (FileOutputStream out = new FileOutputStream(fileName)) { doc.write(out); } } } }

No comments:

Post a Comment