2013-03-27 58 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")); 

如果仍然不工作,请提供堆栈跟踪?它可以帮助。 (如果没有保存文档,必须抛出异常)