Apache POI:替换段落文本 [英] Apache POI: Replace paragraph text
问题描述
我正在使用 Apache POI 从模板生成 docx 文件.似乎没有明显的方法来替换段落中的所有文本,而且文档非常稀缺.现在我可以通过循环阅读文档的段落,然后循环每个段落的运行,然后循环每个运行的文本......这工作得很好,我可以在运行中替换文本的内容,但是我的模板占位符(例如:<>)可能会被分成几个运行,这使得匹配和替换变得非常复杂.有没有办法设置 XWPFParagraph 的内容?或者至少有一种方法可以将段落中的所有运行全部删除并创建我自己的运行?
I am using Apache POI to generate docx files from a template. There doesn't seem to be an obvious way to replace all text in a paragraph and the documentation is pretty scarce. Right now I am able to read a document by looping through its paragraphs, then looping through each paragraph's runs, then looping through each run's text... This works pretty well and I can replace the contents of a text in a run, but my template placeholders (example: <>) may be split into several runs, which makes it really complicated to match and replace. Is there a way to set the contents of a XWPFParagraph? Or at least a way to zap all runs in a paragraph and create my own runs?
这是我目前所拥有的:
public static void main(String[] args) {
InputStream fs = null;
try {
fs = new FileInputStream("C:\\sample1.docx");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
XWPFDocument doc = null;
try {
doc = new XWPFDocument(fs);
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < doc.getParagraphs().length; i++) {
XWPFParagraph paragraph = doc.getParagraphs()[i];
paragraph.getCTP().getRArray().
// This will output the paragraph's contents.
System.out.println(paragraph.getParagraphText());
for (int j = 0; j < paragraph.getCTP().getRArray().length; j++) {
CTR run = paragraph.getCTP().getRArray()[j];
for (int k = 0; k < run.getTArray().length; k++) {
CTText text = run.getTArray()[k];
// This will output the text contents
System.out.println(text.getStringValue());
// And this will set its contents
text.setStringValue("Success!");
}
}
}
try {
doc.write(new FileOutputStream("C:\\output.docx"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
推荐答案
我在 3.7-beta2 中得到了它.该解决方案并不理想并且有点复杂,但它适用于我的用例.现在有一个 XWPFDocument#setParagraph 方法可以解决这个问题......我在我的博客上有几个使用 POI 编写 Word 文档的例子 - tkgospodinov.com:
I got it working with 3.7-beta2. The solution is not ideal and is a little convoluted, but it worked for my use case. There is now a XWPFDocument#setParagraph method that will do the trick... I have a couple of examples of writing Word documents with POI on my blog - tkgospodinov.com:
http://tkgospodinov.com/writing-microsoft-word-documents-in-java-with-apache-poi/
希望有所帮助.
这篇关于Apache POI:替换段落文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!