2014-03-24 1 views
7

템플릿 워드 문서를로드하여 컨텐츠를 추가하고 새 문서로 저장하려고합니다. 나는 .doc 파일을 만들고있다. 워드 문서 템플릿의 변수를 자바로 바꾸기

는 오랜 연구 후 나는 단지 DOCX을위한 솔루션을 발견 : 그 값에 의해 $VAR :

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/

그래서 나는이 형식으로 작성된 모든 변수를 대체합니다. 속도 또는 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

위의 코드를 사용하려면 항아리가 필요합니까? –

+0

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

+0

북마크가 단어 표에 배치 될 때 바뀌지 않습니다. –

-5

Vikrant,

코드 조각은 위 작업을하기 위해 주어진 코드

, 우리는 위에서 언급 한 항아리 필요를 참조하십시오. 그 Jar와 함께, poi-3.5-FINAL.jar도 사용/다운로드하십시오.

희망 사항이 귀하의 질문에 대한 답변입니다.

+3

바와 같이 [아파치 POI의 FAQ - 다른 버전간에 단지 혼합] 설명 (http://poi.apache.org/faq.html#faq-N101F8) (예를 들어 3.2과 3.5 스크래치 -main) **는 지원되지 않습니다 **! 그래서 당신은 누군가에게 지원되지 않는 무언가를하고, [매우 오래된 버전] (http://poi.apache.org/changes.html)을 사용하라고 말하고 있습니다. – Gagravarr