相关文章推荐

I am trying to delete a paragraph from the .docx document i have generated using the Apache poi XWPF. I can do it easily with the .doc word document using HWPF as below :

    for (String paraCount : plcHoldrPargrafDletdLst) {
        Paragraph ph = doc.getRange().getParagraph(Integer.parseInt(paraCount));
        System.out.println("Deleted Paragraph Start & End: " + ph.getStartOffset() +" & " + ph.getEndOffset());
        System.out.println("Deleted Paragraph Test: " + ph.text());
        ph.delete();

I tried to do the same with

doc.removeBodyElement(Integer.parseInt(paraCount));

But unfortunatley not successful enough to get the result as i want. The result document, i cannot see the paragraph deleted.
Any suggestions on how to accompolish the similar functionality in XWPF.

Ok, this question is a bit old and might not be required anymore, but I just found a different solution than the suggested one.

Hope the following code will help somebody with the same issue

FileInputStream fis = new FileInputStream(fileName); XWPFDocument doc = new XWPFDocument(fis); fis.close(); // Find a paragraph with todelete text inside XWPFParagraph toDelete = doc.getParagraphs().stream() .filter(p -> StringUtils.equalsIgnoreCase("todelete", p.getParagraphText())) .findFirst().orElse(null); if (toDelete != null) { doc.removeBodyElement(doc.getPosOfParagraph(toDelete)); OutputStream fos = new FileOutputStream(fileName); doc.write(fos); fos.close();
 
推荐文章