简体   繁体   中英

How to remove line breaks with Apache Poi?

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));
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM