Docx4j测试 - 没有文件输出

时间:2013-03-27 21:18:43

标签: docx4j

尝试用docx4j(http://www.docx4java.org)编写我的第一堂课。基本上,我们的想法是在.docx文件中找到一串文本,并将其替换为另一个文本字符串。基本上是一个邮件合并。虽然我没有收到任何错误,但合并的文档本身并没有保存在我建议的路径中。这让我觉得这是一个文件路径问题,但我没有看到它有任何问题。

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目录具有写入权限。你能看到我的文件路径有什么问题吗?我可能完全走错了路,但这对我来说都是新的,所以我在学习的过程中一直在学习。

非常感谢任何和所有帮助。

1 个答案:

答案 0 :(得分:0)

乍一看,我建议尝试按照以下方式编写您的路径:

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

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

相关问题