Replacing variables in a Word document template with java

I want to download a template word document to add content and save as a new document. I am working on a .doc file.

After much research, I found solutions for docx:

http://www.smartjava.org/content/create-complex-word-docx-documents-programatically-docx4j

http://www.sambhashanam.com/mail-merge-in-java-for-microsoft-word-document-part-i/

Therefore, I want to replace any variable written in this format: $VAR by its value. Can I do it with speed or Apache-poi, for which this is the best solution. Any help would be appreciated.

+7
java apache-poi velocity
source share
2 answers

Yes, you can do this using Apache-POI. Variable names must be unique. See the following code

 import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.usermodel.CharacterRun; import org.apache.poi.hwpf.usermodel.Paragraph; import org.apache.poi.hwpf.usermodel.Range; import org.apache.poi.hwpf.usermodel.Section; import org.apache.poi.poifs.filesystem.POIFSFileSystem; public class HWPFTest { public static void main(String[] args){ String filePath = "F:\\Sample.doc"; POIFSFileSystem fs = null; try { fs = new POIFSFileSystem(new FileInputStream(filePath)); HWPFDocument doc = new HWPFDocument(fs); doc = replaceText(doc, "$VAR", "MyValue1"); saveWord(filePath, doc); } catch(FileNotFoundException e){ e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } } private static HWPFDocument replaceText(HWPFDocument doc, String findText, String replaceText){ Range r1 = doc.getRange(); for (int i = 0; i < r1.numSections(); ++i ) { Section s = r1.getSection(i); for (int x = 0; x < s.numParagraphs(); x++) { Paragraph p = s.getParagraph(x); for (int z = 0; z < p.numCharacterRuns(); z++) { CharacterRun run = p.getCharacterRun(z); String text = run.text(); if(text.contains(findText)) { run.replaceText(findText, replaceText); } } } } return doc; } private static void saveWord(String filePath, HWPFDocument doc) throws FileNotFoundException, IOException{ FileOutputStream out = null; try{ out = new FileOutputStream(filePath); doc.write(out); } finally{ out.close(); } } } 
+18
source share

Vikrant

The code for the fragment is given above, and in order to work, we need to use the jar mentioned above. Along with this Jar, use / download poi-3.5-FINAL.jar as well.

Hope this answers your question.

-5
source share

All Articles