简体   繁体   English

如何使用 Apache Poi 删除换行符?

[英]How to remove line breaks with Apache Poi?

I need to delete line breaks in a document docx.我需要删除文档 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. XWPFParagraph 中的文本由一个或多个 XWPFRun 对象组成 XWPFRun 具有 getText() 和 setText() 方法。 Apache StringUtils.remove(str, remove) removes all occurrences of "remove" from the "str" string. Apache StringUtils.remove(str, remove) 从“str”字符串中删除所有出现的“remove”。

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.注意:Apache StringUtils.remove 是 null 安全的。

This answer is a simplification of the accepted answer to this question: Replacing a text in Apache POI XWPF这个答案是对这个问题的公认答案的简化: Replacing a text in Apache POI XWPF

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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