0

尝试用 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 输入文件确实存在并且上传目录具有写入权限。你能在这里看到我的文件路径有什么问题吗?我可能完全走错了路,但这对我来说都是全新的,所以我边走边学。

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

4

1 回答 1

0

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

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

如果它仍然不起作用,请提供堆栈跟踪?它可以提供帮助。(如果没有保存doc,肯定是抛出异常)

于 2013-05-23T10:48:44.397 回答