How to remove line breaks with Apache Poi?

Viewed 58

I need to delete line breaks in a document docx. My code is this, but it doesn't work with line breaks, only it works with text:

XWPFParagraph toDelete = doc.getParagraphs().stream()
            .filter(p-> StringUtils.equalsAnyIgnoreCase("\n", p.getParagraphText()))
            .findFirst().orElse(null);
    if(toDelete!=null){

        doc.removeBodyElement(doc.getPosOfParagraph(toDelete));
    }
1 Answers

The text in an XWPFParagraph is composed from one or more XWPFRun objects XWPFRun has getText() and setText() methods. Apache StringUtils.remove(str, remove) removes all occurrences of "remove" from the "str" string.

I'm still old-school, here is an imperative (and untested) solution:

for (final XWPFParagraph currentParagraph :  doc.getParagraphs())
{
    for (final XWPFRun currentRun : currentParagraph.getRuns())
    {
        final String strippedText;
        final String text = currentRun.getText(0); // Start at position 0
        
        strippedText = StringUtils.remove(text, "\n");
        
        currentRun.setText(0):
    }
}

Note: Apache StringUtils.remove is null safe.

This answer is a simplification of the accepted answer to this question: Replacing a text in Apache POI XWPF

Related