2014-03-24 47 views
7

我想加載模板word文檔以添加內容並保存爲新文檔。我正在處理.doc文件。用java代替word文檔模板中的變量

經過長期的研究後,我只找到解決方案的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/

所以我想,以取代寫在這個格式的變量:其值$VAR。 我可以用velocity或Apache-poi來做它,最好的解決方案是什麼? 任何幫助將不勝感激。

回答

18

是的,你可以使用Apache-POI來完成。你的變量名稱必須是唯一的。請看下面的代碼

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(); 
     } 
    } 
} 
+0

使用上面的代碼需要哪個jar? –

+0

@SanjayPatel它的Apache POI [https://poi.apache.org/download.html](https://poi.apache.org/download.html) – Liquidpie

+0

它不會替換書籤放在桌上的文字 –

-5

維克蘭特,

的代碼片段上面,並以給定的工作,需要我們上面提到的罐子。除了那個Jar之外,還可以使用/下載poi-3.5-FINAL.jar。

希望這會回答你的問題。

+3

正如解釋[在Apache POI常見問題解答 - 版本之間混合罐子](http://poi.apache.org/faq.html#faq-N101F8)(例如3.2-scratchpad和3.5 - 主)**不支持**!所以你告訴別人做一些不支持的事情,並告訴他們使用[非常舊的版本](http://poi.apache.org/changes.html),不是很大:( – Gagravarr