Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. /*
  2. * Deletes the given paragraph.
  3. */
  4. public static void deleteParagraph(XWPFParagraph p) {
  5. if (p != null) {
  6. List<XWPFRun> runs = p.getRuns();
  7. //Delete all the runs
  8. for (int i = runs.size() - 1; i >= 0; i--) {
  9. p.removeRun(i);
  10. }
  11. p.setPageBreak(false); //Remove the eventual page break
  12. }
  13. }
  14.  
  15. p.setSpacingAfter(0);
  16. p.setSpacingAfterLines(0);
  17. p.setSpacingBefore(0);
  18. p.setSpacingBeforeLines(0);
  19. p.setIndentFromLeft(0);
  20. p.setIndentFromRight(0);
  21. p.setIndentationFirstLine(0);
  22. p.setIndentationLeft(0);
  23. p.setIndentationRight(0);
  24.  
  25. import java.io.*;
  26. import org.apache.poi.xwpf.usermodel.*;
  27.  
  28. import java.awt.Desktop;
  29.  
  30. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  31.  
  32. public class WordRemoveParagraph {
  33.  
  34. /*
  35. * Deletes the given paragraph.
  36. */
  37.  
  38. public static void deleteParagraph(XWPFParagraph p) {
  39. XWPFDocument doc = p.getDocument();
  40. int pPos = doc.getPosOfParagraph(p);
  41. //doc.getDocument().getBody().removeP(pPos);
  42. doc.removeBodyElement(pPos);
  43. }
  44.  
  45. public static void main(String[] args) throws IOException, InvalidFormatException {
  46.  
  47. XWPFDocument doc = new XWPFDocument(new FileInputStream("source.docx"));
  48.  
  49. int pNumber = doc.getParagraphs().size() -1;
  50. while (pNumber >= 0) {
  51. XWPFParagraph p = doc.getParagraphs().get(pNumber);
  52. if (p.getParagraphText().contains("delete")) {
  53. deleteParagraph(p);
  54. }
  55. pNumber--;
  56. }
  57.  
  58. FileOutputStream out = new FileOutputStream("result.docx");
  59. doc.write(out);
  60. out.close();
  61. doc.close();
  62.  
  63. System.out.println("Done");
  64. Desktop.getDesktop().open(new File("result.docx"));
  65.  
  66. }
  67.  
  68. }
  69.  
  70. cell.removeParagraph(cell.getParagraphs().indexOf(para));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement