Monday, 29 February 2016

How to create and update a word document in Java

Below code snippets will help you to create a new word document and update an existing word document. We are using apache poi libraries to access word documents.

Below code will create a word document of name FileName.
                 //Blank Document
                   XWPFDocument document= new XWPFDocument();
                //Write the Document in file system
                   FileOutputStream out = new FileOutputStream(new File(FileName));
                   document.write(out);
                   out.close();

Below code will update a word document of name FileName and will insert a local image.

                   XWPFDocument document = new XWPFDocument(new FileInputStream(FileName));
  XWPFParagraph a = document.createParagraph();
  XWPFRun run=a.createRun();
  run.setText(ImageText);
 
  String imgFile = ImagePath;
  FileInputStream is = new FileInputStream(imgFile);
  run.addBreak();
  run.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, imgFile,                                                  Units.toEMU(500), Units.toEMU(300));
  FileOutputStream out = new FileOutputStream(new File(FileName));
  document.write(out);
  out.close();


Please let me know if you face any issues while using the above code.

No comments:

Post a Comment