0
我有一個包含項目的表。我想設置單詞文檔中的項目名稱,但每個項目都在一個新行中。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」。
的'字符串文本= r.getText(0);'明確地僅獲取第一文本部分從運行,但後'r.setText(文本,0); r.addBreak(); r.setText(「P01」);'有兩個文本部分。一個很好的答案是不可能的,因爲你沒有提供[Minimal,Complete和Verifiable示例](https://stackoverflow.com/help/mcve),但你可以嘗試'String text = r.text();'代替。 –