我已经使用值准备了WordprocessingMLPackage。我有一个带有新换行符的字符串值。我必须生成一个单词报告作为zip文件。
字符串值将替换为单词模板中的字符串,而不会出现换行符。
我试图用w:br替换字符串中的\n
换行符,但它没有帮助。
还有其他方法可以做同样的事情吗?
您不能单独替换文本,您需要单独插入每一行。
你需要做那样的事情:
更换前:
<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()
。这是一个包含<w:t>
文本元素的列表,您可以删除并添加其他元素。
我是这样做的:
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);
}
}
您还可以删除文本元素并添加所有其他元素。希望这能给出一个想法,需要做些什么。