2016-10-31 5 views
2

Apache POIを使用して、Microsoft Word文書から一連の連続した段落を削除しようとしています。XWPFParagraphを削除すると段落記号(¶)が残る

私が理解しているものから、段落を削除すると、このようにその実行のすべてを取り除くことによって可能である。実際には

/* 
* Deletes the given paragraph. 
*/ 
public static void deleteParagraph(XWPFParagraph p) { 
    if (p != null) { 
     List<XWPFRun> runs = p.getRuns(); 
     //Delete all the runs 
     for (int i = runs.size() - 1; i >= 0; i--) { 
      p.removeRun(i); 
     } 
     p.setPageBreak(false); //Remove the eventual page break 
    } 
} 

、それは動作しますが、奇妙な何かがあります。削除された段落のブロックはドキュメントから消えませんが、空の行のセットで変換されます。すべての段落が新しい行に変換されるのと同じです。

コードから段落の内容を印刷すると、実際にはスペースが(それぞれ削除されたため)表示されます。有効なフォーマットマークの可視化と、文書から直接コンテンツを見て、私はこの見ることができます:

enter image description here

を¶の縦の列は削除された要素のブロックに対応しています。

あなたはその考えがありますか?私の段落はに完全にを削除したいと思います。

p.setSpacingAfter(0); 
p.setSpacingAfterLines(0); 
p.setSpacingBefore(0); 
p.setSpacingBeforeLines(0); 
p.setIndentFromLeft(0); 
p.setIndentFromRight(0); 
p.setIndentationFirstLine(0); 
p.setIndentationLeft(0); 
p.setIndentationRight(0); 

をしかし、運を持つ:

私も(setText()で)テキストを置き換えることによって、そして、この方法を自動的に追加することができ、最終的にスペースを削除することで試してみました。

答えて

5

この段落の実行だけを削除するのではなく、段落を削除して段落を削除します。段落の削除は、apache poi高水準APIの一部ではありません。しかし、XWPFDocument.getDocument().getBody()を使用して、我々は低レベルCTBodyを得ることができ、removeP(int i)があります。

例:

import java.io.*; 
import org.apache.poi.xwpf.usermodel.*; 

import java.awt.Desktop; 

import org.apache.poi.openxml4j.exceptions.InvalidFormatException; 

public class WordRemoveParagraph { 

/* 
    * Deletes the given paragraph. 
    */ 

public static void deleteParagraph(XWPFParagraph p) { 
    XWPFDocument doc = p.getDocument(); 
    int pPos = doc.getPosOfParagraph(p); 
    //doc.getDocument().getBody().removeP(pPos); 
    doc.removeBodyElement(pPos); 
} 

public static void main(String[] args) throws IOException, InvalidFormatException { 

    XWPFDocument doc = new XWPFDocument(new FileInputStream("source.docx")); 

    int pNumber = doc.getParagraphs().size() -1; 
    while (pNumber >= 0) { 
    XWPFParagraph p = doc.getParagraphs().get(pNumber); 
    if (p.getParagraphText().contains("delete")) { 
    deleteParagraph(p); 
    } 
    pNumber--; 
    } 

    doc.write(new FileOutputStream("result.docx")); 
    doc.close(); 

    System.out.println("Done"); 
    Desktop.getDesktop().open(new File("result.docx")); 

} 

} 

これは、テキストは、「削除」が含まとresult.docxで結果を保存し、文書のsource.docxからすべての段落を削除します。


編集:

doc.getDocument().getBody().removeP(pPos);が、作品は、それがXWPFDocumentの段落のリストは更新されません。したがって、リストを再度読み込んでいる間だけリストが更新されるため、段落イテレータやそのリストへの他のアクセスが破壊されます。

したがって、代わりにdoc.removeBodyElement(pPos);を使用する方が良いでしょう。 posが文書本体のページ区切りを指している場合は、はdoc.getDocument().getBody().removeP(pos);とまったく同じです。その段落はBodyElementでもあります。さらに、XWPFDocumentの段落リストを更新します。

+0

グレート、ありがとうございました! –

1

あなたがあなたの代わりにXWPFDocumentXWPFTableCellの機能を使用する必要があるテーブルの内側にある:

cell.removeParagraph(cell.getParagraphs().indexOf(para)); 
関連する問題