简体   繁体   English

使用Apache POI(Java)用表格替换.docx中的文本

[英]Replacing text in .docx with a table, using Apache POI (Java)

So, I'm trying to insert a table at a certain point in a .docx file using Apache POI (Vers. 3.15). 因此,我正在尝试使用Apache POI(版本3.15)在.docx文件中的特定位置插入表。 I'm able to create it, using the code below. 我可以使用下面的代码创建它。 That throws the table that I need into the end of the document. 那把我需要的表扔到了文件的末尾。 (If this is superfluous, my apologies! Trying to give as much info as possible!) (如果这是多余的,我表示歉意!尝试提供尽可能多的信息!)

    /* Creates table for the questions */
private XWPFTable createMainTable(XWPFDocument doc, ArrayList<String> qs, ArrayList<String> avgScores, ArrayList<String> favScores){ 
    XWPFTable table = doc.createTable();

    int currRow = 0;
    for(String q : qs){
        XWPFTableRow curRow = table.getRow(currRow);
        if(currRow == 0){
            curRow.getCell(0).setText("Question");
        }else{
        curRow.getCell(0).setText(q);
        }
        if(currRow < qs.size()-1){
            table.createRow();
            currRow++;
        }else{
            currRow++;
        }
    }
    currRow = 0;
    for(String avg : avgScores){
        XWPFTableRow curRow = table.getRow(currRow);
        curRow.addNewTableCell();
        if(currRow == 0){
            curRow.getCell(1).setText(" Average Score ");
        }else{
            curRow.getCell(1).setText(avg);
        }
        currRow++;    
    }
    currRow = 0;
    for(String fav : favScores){
        XWPFTableRow curRow = table.getRow(currRow);
        curRow.addNewTableCell();
        if(currRow == 0){
            curRow.getCell(2).setText(" Favorable Score ");
        }else{
            curRow.getCell(2).setText(fav);
        }
        currRow++;
    }
    return table;
}

Now, in order to replace the rest of the text in the document, I use the following method: 现在,为了替换文档中的其余文本,我使用以下方法:

    /* Replace text in the document */
private long replaceText(ArrayList<String> comments, String targ, XWPFDocument doc) {
long count = 0;
for (XWPFParagraph paragraph : doc.getParagraphs()) {
  List<XWPFRun> runs = paragraph.getRuns();

    StringBuilder sb = new StringBuilder();
    for (String c : comments){
        sb.append(c);
        sb.append("|");
    }
    String find = targ;
    String repl = sb.toString();
    TextSegement found = paragraph.searchText(find, new PositionInParagraph());
    if ( found != null ) {
      count++;
      if ( found.getBeginRun() == found.getEndRun() ) {
        // whole search string is in one Run
        XWPFRun run = runs.get(found.getBeginRun());
        String runText = run.getText(run.getTextPosition());
        String replaced = runText.replace(find, repl);
        run.setText(replaced, 0);
      } else {
        // The search string spans over more than one Run
        // Put the Strings together
        StringBuilder b = new StringBuilder();
        for (int runPos = found.getBeginRun(); runPos <= found.getEndRun(); runPos++) {
          XWPFRun run = runs.get(runPos);
          b.append(run.getText(run.getTextPosition()));
        }                       
        String connectedRuns = b.toString();
        String replaced = connectedRuns.replace(find, repl);

        // The first Run receives the replaced String of all connected Runs
        XWPFRun partOne = runs.get(found.getBeginRun());
        partOne.setText(replaced, 0);
        // Removing the text in the other Runs.
        for (int runPos = found.getBeginRun()+1; runPos <= found.getEndRun(); runPos++) {
          XWPFRun partNext = runs.get(runPos);
          partNext.setText("", 0);
        }                          
      }
    }     
}
return count;}  

What that 2nd method does is find a certain keyword in the document, and replace it with a String. 第二种方法所做的是在文档中找到一个特定的关键字,并将其替换为String。 Right now, it's passed an ArrayList, but that changes as I'm trying different things out. 现在,它已经传递了ArrayList,但是随着我尝试不同的事情而改变了。 I was able to get the memory address of the table to print out (by changing the input to an XWPFTable), but that's as far as I was able to get. 我能够获得要打印的表的内存地址(通过将输入更改为XWPFTable),但是这是我所能获得的。 I feel like I'm missing something stupid, but I just can't figure it out. 我觉得我想念一些愚蠢的东西,但我只是想不通。

Much thanks to Axel , I was able to get the desired result! 非常感谢Axel ,我能够获得理想的结果! I changed my creation method a little bit, and passed it just an empty table to fill. 我稍稍更改了创建方法,并将其传递给一个空表以进行填充。 Then, using the cursor like Axel suggested, it now finds the target string ("%TABLE"), and replaces it with the table, exactly as I needed. 然后,使用像Axel建议的游标,它现在找到目标字符串(“%TABLE”),并完全按照我的需要将其替换为表。

    /* Replaces table */
private long replaceTable(XWPFDocument doc, ArrayList<String> qs, ArrayList<String> avgScores, ArrayList<String> favScores) {
    XWPFTable table = null;
    long count = 0;
     for (XWPFParagraph paragraph : doc.getParagraphs()) {
       List<XWPFRun> runs = paragraph.getRuns();
         String find = "%TABLE";
         TextSegement found = paragraph.searchText(find, new PositionInParagraph());
         if ( found != null ) {
           count++;
           if ( found.getBeginRun() == found.getEndRun() ) {
             // whole search string is in one Run
             XmlCursor cursor = paragraph.getCTP().newCursor();
             table = doc.insertNewTbl(cursor);
             XWPFRun run = runs.get(found.getBeginRun());
             // Clear the "%TABLE" from doc
            String runText = run.getText(run.getTextPosition());
            String replaced = runText.replace(find, "");
            run.setText(replaced, 0);
           } else {
             // The search string spans over more than one Run
             StringBuilder b = new StringBuilder();
             for (int runPos = found.getBeginRun(); runPos <= found.getEndRun(); runPos++) {
               XWPFRun run = runs.get(runPos);
               b.append(run.getText(run.getTextPosition()));
             }                       
             String connectedRuns = b.toString();
             XmlCursor cursor = paragraph.getCTP().newCursor();
             table = doc.insertNewTbl(cursor);
             String replaced = connectedRuns.replace(find, ""); // Clear search text

             // The first Run receives the replaced String of all connected Runs
             XWPFRun partOne = runs.get(found.getBeginRun());
             partOne.setText(replaced, 0);
             // Removing the text in the other Runs.
             for (int runPos = found.getBeginRun()+1; runPos <= found.getEndRun(); runPos++) {
               XWPFRun partNext = runs.get(runPos);
               partNext.setText("", 0);
             }
           }
         }     
     }
     fillTable(table, qs, avgScores, favScores);
     return count;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM