更新XWPFParagraph的使用Apache POI文 [英] Updating the text of a XWPFParagraph using Apache POI
问题描述
我已经在文档中能够遍历所有的段落,并在文本和得到的一切,我已阅读并理解了如何从头开始创建一个文档。但我怎么能更新和替换段落中的文字?我可以做 createRun
段落,但将只是它创建一个新的一段文字。
I have been able to loop through all paragraphs in a document and get at the text and everything and I have read and understood how you can create a document from scratch. But how can I update and replace the text in a paragraph? I can do createRun
in a paragraph but that will just create a new piece of text in it.
...
FileInputStream fis = new FileInputStream("Muu.docx");
XWPFDocument myDoc = new XWPFDocument(fis);
XWPFParagraph[] myParas = myDoc.getParagraphs();
...
我的理论是,我需要在我想改变,或者删除该段,并重新添加)段现有的运行,但我不能找到方法来做到这一点。
My theory is that I need to get at the existing "run" in the paragraph I want to change, or delete the paragraph and add it again) but I cannot find methods to do that.
推荐答案
您不能在XWPFParagraph直接更改文本。一个XWPFParagraph是由一个或多个XWPFRun实例。这些提供了设置文本的方式。
You can't change the text on a XWPFParagraph directly. A XWPFParagraph is made up of one or more XWPFRun instances. These provide the way to set the text.
要更改文本,你的code会想是这样的:
To change the text, your code would want to be something like:
public void changeText(XWPFParagraph p, String newText) {
List<XWPFRun> runs = p.getRuns();
for(int i = runs.size() - 1; i > 0; i--) {
p.removeRun(i);
}
XWPFRun run = runs.get(0);
run.setText(newText, 0);
}
这将确保你只有一个文本串(第一个),并将取代所有文字是你提供了什么。
That will ensure you only have one text run (the first one), and will replace all the text to be what you provided.
这篇关于更新XWPFParagraph的使用Apache POI文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!