簡體   English   中英

如何使用 Apache Poi 刪除換行符?

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

我需要刪除文檔 docx 中的換行符。 我的代碼是這樣的,但它不適用於換行符,只能用於文本:

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

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

XWPFParagraph 中的文本由一個或多個 XWPFRun 對象組成 XWPFRun 具有 getText() 和 setText() 方法。 Apache StringUtils.remove(str, remove) 從“str”字符串中刪除所有出現的“remove”。

我還是老派,這是一個必要的(未經測試的)解決方案:

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

注意:Apache StringUtils.remove 是 null 安全的。

這個答案是對這個問題的公認答案的簡化: Replacing a text in Apache POI XWPF

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM