Write Word File Example
This program demonstrates writing text into a Word file.
Problem Statement
Write a Java program that creates a Word .docx file with text using Apache POI.
Source Code
| 1 | import java.io.*; |
| 2 | import org.apache.poi.xwpf.usermodel.*; |
| 3 | public class WriteWordExample { |
| 4 | public static void main(String[] args) { |
| 5 | System.out.println("Eduinq Write Word Example"); |
| 6 | XWPFDocument doc=new XWPFDocument(); |
| 7 | XWPFParagraph p=doc.createParagraph(); |
| 8 | XWPFRun run=p.createRun(); |
| 9 | run.setText("Eduinq Word Writing Example"); |
| 10 | try(FileOutputStream fos=new FileOutputStream("output.docx")) { |
| 11 | doc.write(fos); |
| 12 | System.out.println("Eduinq Word Written Successfully"); |
| 13 | } catch(IOException e) { |
| 14 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 15 | } |
| 16 | } |
| 17 | } |
Program Output
Eduinq Write Word Example Eduinq Word Written Successfully
Explanation
Apache POI XWPFDocument creates .docx files. - XWPFRun writes text into paragraphs. - Exception handling ensures safe operations. - In enterprise systems, Word writing is used for reports and letters. Conclusion: Shows writing Word files.