Apache-poi-word-paragraph

提供:Dev Guides
移動先:案内検索

Apache POI Word-段落

この章では、段落を作成する方法と、Javaを使用して文書に段落を追加する方法を学習します。 段落は、Wordファイルのページの一部です。

この章を完了すると、段落を作成し、読み取り操作を実行できるようになります。

段落を作成する

まず、前の章で説明した参照クラスを使用して段落を作成しましょう。 前の章に従って、最初にドキュメントを作成し、次に段落を作成できます。

次のコードスニペットは、スプレッドシートを作成するために使用されます-

//Create Blank document
   XWPFDocument document = new XWPFDocument();

//Create a blank spreadsheet
   XWPFParagraph paragraph = document.createParagraph();

段落で実行

*Run* を使用して、テキストまたは任意のオブジェクト要素を入力できます。 Paragraphインスタンスを使用して、*実行*を作成できます。

次のコードスニペットを使用して、Runを作成します。

XWPFRun run = paragraph.createRun();

段落に書き込む

文書にテキストを入力してみましょう。 以下のテキストデータを考慮してください-

At finddevguides.com, we strive hard to provide quality tutorials for self-learning
purpose in the domains of Academics, Information Technology, Management and Computer
Programming Languages.

次のコードは、上記のデータを段落に書き込むために使用されます。

import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class CreateParagraph {

   public static void main(String[] args)throws Exception {

     //Blank Document
      XWPFDocument document = new XWPFDocument();

     //Write the Document in file system
      FileOutputStream out = new FileOutputStream(new File("createparagraph.docx"));

     //create Paragraph
      XWPFParagraph paragraph = document.createParagraph();
      XWPFRun run = paragraph.createRun();
      run.setText("At finddevguides.com, we strive hard to " +
         "provide quality tutorials for self-learning " +
         "purpose in the domains of Academics, Information " +
         "Technology, Management and Computer Programming
         Languages.");

      document.write(out);
      out.close();
      System.out.println("createparagraph.docx written successfully");
   }
}

上記のJavaコードを* CreateParagraph.java、*として保存し、次のようにコマンドプロンプトからコンパイルして実行します-

$javac CreateParagraph.java
$java CreateParagraph

現在のディレクトリに createparagraph.docx という名前のWordファイルを生成するためにコンパイルおよび実行され、コマンドプロンプトで次の出力が表示されます-

createparagraph.docx written successfully
*createparagraph.docx* ファイルは次のようになります。

段落の作成