Apache-poi-word-tables

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

Apache POI Word-テーブル

この章では、ドキュメントにデータのテーブルを作成する方法を学びます。 XWPFTable クラスを使用して、テーブルデータを作成できます。 各 Row をテーブルに追加し、各 cellRow に追加すると、テーブルデータが取得されます。

テーブルを作成

次のコードは、ドキュメント内のテーブルを作成するために使用されます-

import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

public class CreateTable {

   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("create_table.docx"));

     //create table
      XWPFTable table = document.createTable();

     //create first row
      XWPFTableRow tableRowOne = table.getRow(0);
      tableRowOne.getCell(0).setText("col one, row one");
      tableRowOne.addNewTableCell().setText("col two, row one");
      tableRowOne.addNewTableCell().setText("col three, row one");

     //create second row
      XWPFTableRow tableRowTwo = table.createRow();
      tableRowTwo.getCell(0).setText("col one, row two");
      tableRowTwo.getCell(1).setText("col two, row two");
      tableRowTwo.getCell(2).setText("col three, row two");

     //create third row
      XWPFTableRow tableRowThree = table.createRow();
      tableRowThree.getCell(0).setText("col one, row three");
      tableRowThree.getCell(1).setText("col two, row three");
      tableRowThree.getCell(2).setText("col three, row three");

      document.write(out);
      out.close();
      System.out.println("create_table.docx written successully");
   }
}

上記のコードを* CreateTable.java。*という名前のファイルに保存し、次のようにコンパイルしてコマンドプロンプトから実行します-

$javac CreateTable.java
$java CreateTable

現在のディレクトリに createtable.docx という名前のWordファイルを生成し、コマンドプロンプトに次の出力を表示します-

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

テーブルの作成