1

我使用 docx4j 从 doc 模板实现了 doc 生成。具有占位符的模板,在我的代码中,将占位符替换为一个值。问题是 docx4j 不能将占位符作为单独的实体。例如:模板是“tempnew.docx”

         welcome to <<name>>,Have a nice day in <<name>>

after running the script, i got the retrieved texts "welcome ", "to", " <<", "name>>" etc.. (check the values of 'content' each time inside the for loop in method 'replaceParagraph' of line     'Text content = (Text) t;')

instead of "welcome ", "to ", "<<name>>" etc..

我的代码:

    public static void main(String[] args) throws IOException, Docx4JException {
       GenerateDoc genDoc = new GenerateDoc();
    String templateFile = "C:\\testdoc\\tempnew.docx";
    WordprocessingMLPackage object = genDoc.getTemplate(templateFile);

    String toAdd = "India";
    genDoc.replaceParagraph( toAdd, object, object.getMainDocumentPart());
    genDoc.writeDocxToStream(object, "C:\\testdoc\\docgen.docx");
}


   private static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {
    List<Object> result = new ArrayList<Object>();
    if (obj instanceof JAXBElement) obj = ((JAXBElement<?>) obj).getValue();

    if (obj.getClass().equals(toSearch))
        result.add(obj);
    else if (obj instanceof ContentAccessor) {
        List<?> children = ((ContentAccessor) obj).getContent();
        for (Object child : children) {
            result.addAll(getAllElementFromObject(child, toSearch));
        }

    }
    return result;
}

      private void replaceParagraph( String textToAdd, WordprocessingMLPackage template, ContentAccessor addTo) {

    // 1. get the paragraph
     String pholderStart ="<<";
     String pholderEnd =">>";
     int placeHolderStartIndex, placeHolderEndIndex;

    List<Object> paragraphs = getAllElementFromObject(template.getMainDocumentPart(), P.class);

    P toReplace = null;
    for (Object p : paragraphs) {
    List<Object> texts = getAllElementFromObject(p, Text.class);
    for (Object t : texts) {
    Text content = (Text) t;
    ...
           ..........}..}
4

2 回答 2

0

如果我理解正确,我猜在您的文档中,“<<”和“>>”被分成单独的运行。

有关解决方案,请参阅变量准备。

于 2013-05-08T12:01:59.677 回答
0

不要重新发明轮子:

 String inputfilepath = "C:\\template2.docx";
 String outputfilepath = "OUT_VariableReplace.docx";
 WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
                    .load(new java.io.File(inputfilepath));
 MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
 HashMap<String, String> mappings = new HashMap<String, String>();
 mappings.put("name", "Hamza Guen");
 documentPart.variableReplace(mappings);
 SaveToZipFile saver = new SaveToZipFile(wordMLPackage);
 saver.save(outputfilepath);

在您的模板中,您可以使用 ${name} 作为占位符。您可以查看VariableReplace文档以获取更多信息。

于 2014-10-29T13:29:41.523 回答