【问题标题】:How to add new line in docx file generation using DOCX4J如何使用 DOCX4J 在 docx 文件生成中添加新行
【发布时间】:2018-05-23 04:43:36
【问题描述】:

我已经准备好带有这些值的 WordprocessingMLPackage。我有一个带有新换行符的字符串值。我必须生成一个 zip 文件的 word 报告。

字符串值被替换为它在单词模板中的样子,没有换行符。

我尝试用 w:br 替换字符串中的 \n 换行符,但没有帮助。

还有其他方法可以做同样的事情吗?

【问题讨论】:

    标签: newline


    【解决方案1】:

    你不能单独替换文本,你需要单独插入每一行。

    你需要这样做:

    替换前:

    <w:p>
        <w:r>
            <w:t>MY_PLACEHOLDER</w:t>
        </w:r>
    </w:p>
    

    替换后:

    <w:p>
        <w:r>
            <w:t>Beforeline break</w:t>
            <w:br/>
            <w:t>After line break</w:t>
        </w:r>
    </w:p>
    

    要实现这一点,您需要封闭元素(在本例中为 Run-Element)。在这个元素上你可以做getContent()。那是一个列表,其中包含&lt;w:t&gt; 文本元素,您可以删除和添加其他元素。

    我是这样做的:

         Text text; //Text object where the substitution should take place
         Run run; // Run object that encloses the Placeholder (parent of text)
         List<String> dataLines; //List of Lines to be inserted
    
         // ...
         // some code to
         // * get the Text object where the substitution should take place
         // * get Run object (which can be cast to ContentAccessor)
         // * get List of to be inserted values
    
         //get list of content of run element (in the example it will be the text object with value MY_PLACEHOLDER)
         List<Object> content = ((ContentAccessor) run).getContent();
    
         //go through the content that needs to be inserted
         for (int i = 0; i < dataLines.size(); i++)
         {
            if (i == 0)
            {
               // if it is the first line, replace MY_PLACEHOLDER with the first line
               text.setValue(dataLines.get(i));
            }
            else
            {
               // else add line breaks and other text elements
               Br lineBreak = new Br();
               content.add(lineBreak);
    
               Text t2 = (Text) XmlUtils.deepCopy(text);
               t2.setValue(dataLines.get(i));
    
               //content can also be added at an index if necessary (otherwise they are added at the end)
               content.add(t2);
            }
         }
    

    您还可以删除文本元素并添加所有其他元素。希望这能给出一个想法,需要做什么。

    【讨论】:

      猜你喜欢
      • 2013-04-08
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多