XWPFDocument替换循环中的paragraphe
问题描述:
我有一个包含项目的表。我想设置单词文档中的项目名称,但每个项目都在一个新行中。XWPFDocument替换循环中的paragraphe
所以我创建了下面的空隙:
当我的文本包含“P01”我更换由名称的文本,添加一个新行,并设置其他文本“P01”。
public void findAndRemplaceString(XWPFDocument doc, String champs) throws IOException {
for (XWPFParagraph p : doc.getParagraphs()) {
java.util.List<XWPFRun> runs = p.getRuns();
if (runs != null) {
for (XWPFRun r : runs) {
String text = r.getText(0);
if (text != null && text.contains("P01")) {
text = text.replace("P01", champs);
System.out.println("text replaced");
r.setText(text, 0);
//add new line
r.addBreak();
//new "P01" added
r.setText("P01");
}
}
}
}
}
因此,项目的下一个名称将在下面的段落中被替换。
@FXML
void endButton(ActionEvent event) {
String file = "model";
for (Person item : table.getItems()) {
//get the name of item
String a = item.getName();
// get the index of item
int ind0 = table.getItems().indexOf(item);
int ind1 = table.getItems().indexOf(item) + 1;
try {
XWPFDocument doc = new XWPFDocument(new FileInputStream(new File(file + ind0 + ".docx")));
findAndRemplaceString(doc, a);
FileOutputStream fileOutputStream = new FileOutputStream(new File(file + ind1 + ".docx"));
doc.write(fileOutputStream);
fileOutputStream.close();
doc.close();
} catch (Exception e) {
System.out.println("erreur " + e);
}
}
}
的问题是:
它仅更换项目的名字,而不是其他人。它不会读取我设置的新“P01”。
答
我找到了答案,它不是最好的,但它的工作原理。
我改变的String []的类型,而不是字符串,这样我可以这样来做:
public void findAndRemplaceString(XWPFDocument doc,String champs[]){
for (XWPFParagraph p : doc.getParagraphs()) {
java.util.List<XWPFRun> runs = p.getRuns();
if (runs != null) {
for (XWPFRun r : runs) {
String text = r.getText(0);
if (text != null && text.contains("P01")) {
for (int i=0;i<champs.length;i++){
text = text.replace("P01","");
r.setText(text,0); //Replace the old text
r.setText(champs[i]);//add the new text
r.addBreak(); //new line
}
}
}
}
}
}
当我按一下按钮,虚空findAndReplaceString只调用一次,而不是循环,所以我把所有的项目名称在那样的列表:
@FXML void endButton(ActionEvent event) {
List<String> list = new ArrayList<String>();
for (Person item : table.getItems()) {
String a = item.getName();
list.add(a);
}
String[] simpleArray = new String[list.size()];
list.toArray(simpleArray);
try{
XWPFDocument doc = new XWPFDocument(new FileInputStream(new File("input.docx")));
findAndRemplaceString(doc,simpleArray);
FileOutputStream fileOutputStream = new FileOutputStream(new File("output.docx"));
doc.write(fileOutputStream);
fileOutputStream.close();
doc.close();
}catch (Exception e) {
System.out.println("erreur " + e);
}
}
的'字符串文本= r.getText(0);'明确地仅获取第一文本部分从运行,但后'r.setText(文本,0); r.addBreak(); r.setText(“P01”);'有两个文本部分。一个很好的答案是不可能的,因为你没有提供[Minimal,Complete和Verifiable示例](https://stackoverflow.com/help/mcve),但你可以尝试'String text = r.text();'代替。 –