2013-03-27 57 views
0

試圖用docx4j(http://www.docx4java.org)寫我的第一堂課。基本上這個想法是在.docx文件中找到一串文本,並將其替換爲另一個文本字符串。本質上是一個郵件合併。儘管我沒有收到任何錯誤,但合併文檔本身並未保存在我建議的路徑中。這讓我認爲這是一個文件路徑問題,但我沒有看到任何問題。Docx4j測試 - 沒有文件輸出

package efi.mailmerge.servlets; 

import java.util.List; 
import javax.xml.bind.JAXBElement; 
import org.docx4j.openpackaging.exceptions.Docx4JException; 
import org.docx4j.openpackaging.packages.WordprocessingMLPackage; 
import org.docx4j.wml.Text; 

public class WordDocTest { 

    /** 
    * Open word document /Users/Jeff/Development/ReServe-Unleashed/Dev/MailMerge/uploads/Sample.docx, replace a piece of text and save 
    * the result to /Users/Jeff/Development/ReServe-Unleashed/Dev/MailMerge/uploads/Sample-Out.docx. 
    * 
    * The text <<CUS_FNAME>> will be replaced with John. 
    * 
    * @param args 
    */ 
    public static void main(String[] args) { 

     // Text nodes begin with w:t in the word document 
     final String XPATH_TO_SELECT_TEXT_NODES = "//w:t"; 

     try { 
      // Open the input file 
      WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File("/Users/Jeff/Development/ReServe-Unleashed/Dev/MailMerge/uploads/Sample.docx")); 

      // Build a list of "text" elements 
      List texts = wordMLPackage.getMainDocumentPart().getJAXBNodesViaXPath(XPATH_TO_SELECT_TEXT_NODES, true); 

      // Loop through all "text" elements 
      for (Object obj : texts) { 
       Text text = (Text) ((JAXBElement) obj).getValue(); 

       // Get the text value 
       String textValueBefore = text.getValue(); 

       // Perform the replacement 
       String textValueAfter = textValueBefore.replaceAll("<<CUS_FNAME>>", "John"); 

       // Show the element before and after the replacement 
       System.out.println("textValueBefore = " + textValueBefore); 
       System.out.println("textValueAfter = " + textValueAfter); 

       // Update the text element now that we have performed the replacement 
       text.setValue(textValueAfter); 

      } 

      wordMLPackage.save(new java.io.File("/Users/Jeff/Development/ReServe-Unleashed/Dev/MailMerge/uploads/Sample-Out.docx")); 

     } catch (Docx4JException e) { 
      Logger.getLogger(WordDocTest.class.getName()).log(Level.SEVERE, null, e); 
      e.printStackTrace(); 
     } catch (Exception e) { 
      Logger.getLogger(WordDocTest.class.getName()).log(Level.SEVERE, null, e); 
      e.printStackTrace(); 
     } 
    } 

} 

在第26行和第50行,您可以看到輸入/輸出路徑。我已經確認Sample.docx輸入文件確實存在,並且uploads目錄具有寫入權限。你能在這裏看到我的文件路徑有什麼問題嗎?我可能會完全走錯路,但這對我來說都是非常新的,所以我一直在學習。

任何和所有的幫助,非常感謝。

+0

也許你正在得到一個異常,但沒有看到它。嘗試添加System.out.println(e.getMessage())。 printStackTrace()寫入標準錯誤流。 – JasonPlutext 2013-03-27 22:01:07

+0

你是從命令行運行的嗎?從IDE?或一個servlet環境? – JasonPlutext 2013-03-27 22:03:42

回答

0

乍一看,我建議嘗試與您的路徑寫了下面的方法:

wordMLPackage.save(new java.io.File("\\Users\\Jeff\\Development\\ReServe-Unleashed\\Dev\\MailMerge\\uploads\\Sample-Out.docx")); 

如果仍然不工作,請提供堆棧跟蹤?它可以幫助。 (如果沒有保存文檔,必須拋出異常)