替换包含Apache POI中的选项卡的表列值

时间:2018-07-28 06:24:31

标签: java apache apache-poi

我需要在word文档中的四个简单段落中替换单词。这些段落包含在表格单元格中。我可以轻松访问这些段落,但是替换无效。

我尝试使用this中的代码

private long replaceInParagraphs(Map<String, String> replacements, List<XWPFParagraph> xwpfParagraphs) {
long count = 0;
for (XWPFParagraph paragraph : xwpfParagraphs) {
  List<XWPFRun> runs = paragraph.getRuns();

  for (Map.Entry<String, String> replPair : replacements.entrySet()) {    
    String find = replPair.getKey();
    String repl = replPair.getValue();
    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;

}

我尝试使用Josh的最佳解决方案。它非常适合单个单词,但不适用于制表符。

四个段落的集合如下:

Number:\t123.10
Work:\tdone
Date:\t
Worker:\t

对于前两行,我可以分割字符串并替换'123.10'和'done'字符串。

但是我该如何处理最后一行?我没有找到替换制表符的解决方案?有想法吗?

0 个答案:

没有答案
相关问题