Append Text to Word Example
This program demonstrates appending text into an existing Word file.
Problem Statement
Write a Java program that appends a new paragraph into a Word .docx file.
Source Code
| 1 | import java.io.*; |
| 2 | import org.apache.poi.xwpf.usermodel.*; |
| 3 | public class AppendWordExample { |
| 4 | public static void main(String[] args) { |
| 5 | System.out.println("Eduinq Append Word Example"); |
| 6 | try(FileInputStream fis=new FileInputStream("output.docx")) { |
| 7 | XWPFDocument doc=new XWPFDocument(fis); |
| 8 | XWPFParagraph p=doc.createParagraph(); |
| 9 | XWPFRun run=p.createRun(); |
| 10 | run.setText("Eduinq Appended Paragraph"); |
| 11 | try(FileOutputStream fos=new FileOutputStream("output.docx")) { |
| 12 | doc.write(fos); |
| 13 | System.out.println("Eduinq Word Appended Successfully"); |
| 14 | } |
| 15 | } catch(Exception e) { |
| 16 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 17 | } |
| 18 | } |
| 19 | } |
Program Output
Eduinq Append Word Example Eduinq Word Appended Successfully
Explanation
Appending adds new paragraphs to existing document. - Uses createParagraph() and createRun(). - Exception handling ensures safe operations. - In enterprise systems, appending Word files is used for incremental updates. Conclusion: Shows appending text to Word files.