Advertisement
meGAmeS1

Apache POI - Replace content in XWPFParagraph

Jun 10th, 2015
538
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. // Before using the function, I'm sure that: paragraph.getText().contains("<#" + tag + "#>") == true
  2. private static void editParagraphWithData(XWPFParagraph paragraph, String tag, String remplacement) {
  3.     int currentRun = 0;
  4.     List<Integer> runsToRemove = new LinkedList<Integer>();
  5.     StringBuilder newText = new StringBuilder();
  6.     int runToEdit = 0;
  7.     String surroundedTag = "<#" + tag + "#>";
  8.    
  9.     // Until we didn't find the tag
  10.     while (!newText.toString().contains(surroundedTag)) {
  11.        
  12.         // Until we didn't find the first corresponding run
  13.         while (paragraph.getRuns().size() > currentRun  && !paragraph.getRuns().get(currentRun).text().contains("<#")) {
  14.             currentRun++;
  15.         }
  16.        
  17.         runToEdit = currentRun;
  18.         newText.append(paragraph.getRuns().get(runToEdit).text());
  19.        
  20.         currentRun++;
  21.        
  22.         // Until we didn't find the end of the tag if it's divided in many runs
  23.         while (paragraph.getRuns().size() > currentRun && !paragraph.getRuns().get(currentRun).text().contains("#>")) {
  24.             runsToRemove.add(currentRun);
  25.             newText.append(paragraph.getRuns().get(currentRun).text());
  26.             currentRun++;
  27.         }
  28.        
  29.         // If we didn't find the right tag
  30.         if (!newText.toString().contains(surroundedTag)) {
  31.             runsToRemove.clear();
  32.             newText = new StringBuilder();
  33.         }
  34.     }
  35.    
  36.     // Replace the tag
  37.     paragraph.getRuns().get(runToEdit).setText(newText.toString().replaceAll(surroundedTag, remplacement), 0);
  38.    
  39.     // Remove the remaining tags if we need to (in reverse order)
  40.     Collections.reverse(runsToRemove);
  41.     for (Integer runToRemove : runsToRemove) {
  42.         paragraph.removeRun(runToRemove);
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement