我有一个包含项目的表。我想设置word文档中的项目名称,但每个项目都在一个新行中。
所以我创建了下面的空白:
当我的文字包含“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”。
答案 0 :(得分:0)
我找到了答案,它不是最好的,但它确实有效。
我改变了String []的类型而不是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
}
}
}
}
}
}
当我单击按钮时,void 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);
}
}