LoginSignup
0
0

Word文書で表を作成または読み取る方法【Java】

Last updated at Posted at 2022-12-29

Microsoft Wordの表は、データを表示するための便利なツールです。大量のデータを行と列のグリッドを使って並べることができるので、読者はより簡単に読み、分析することができます。この記事では、Free Spire.Doc for Javaライブラリを使用して、JavaでWord文書内の表を作成したり、読んだりする方法を紹介します。

【依存関係の追加】

この方法は、無料のFree Spire.Doc for Javaが必要ですので、先にjarファイルをインポートしてください。

1. Maven

Maven を使用している場合、プロジェクトの pom.xml ファイルに以下のコードを追加することで、簡単にアプリケーションに JAR ファイルをインポートすることができます。

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc.free</artifactId>
        <version>5.2.0</version>
    </dependency>
</dependencies>

2. 公式サイトよりJarファイルをダウンロード

まず、Free Spire.Doc for Javaの公式サイトよりzipファイルをダウンロードします。zipファイルを解凍し、libフォルダの下にあるSpire.Doc.jarファイルを依存関係としてプロジェクトにインポートしてください。

Word文書に表を作成する

Free Spire.Doc for Java は、Word 文書の特定のセクションに表を追加する Section.addTable() メソッドを提供します。表が追加されると、その表に対して、表セルの水平/垂直方向の結合、データの追加、書式の適用など、さまざまな操作を行うことができます。詳しい手順は以下の通りです。

  • Document クラスのインスタンスを生成し、Document.loadFromFile() メソッドを使用してWord文書を読み込みます。
  • Document.getSections().get(int) メソッドを使用して、インデックスで特定のセクションを取得します。
  • 表のヘッダー行とデータ行のデータを定義し、それぞれ一次元の文字列配列と二次元の文字列配列に格納します。
  • Section.addTable() メソッドを使用して、セクションに表を追加します。
  • Table.resetCells() メソッドを使用して、データの長さに応じて表の行と列の数を指定します。
  • Table.applyHorizontalMerge() メソッドを使用して、表の特定のセルを水平方向にマージしています。
  • 表のヘッダー行のデータと書式を設定します。
  • 表のデータ行のデータと書式を設定します。
  • 表の特定の行の背景色を設定します。
  • Document.saveToFile() メソッドを使用して、結果ドキュメントを保存します。

Java

import com.spire.doc.*;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TableRowHeightType;
import com.spire.doc.documents.VerticalAlignment;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class createTable {
    public static void main(String []args) {
        //Document クラスのインスタンスを作成する
        Document document = new Document();
        //Word文書を読み込む
        document.loadFromFile("社員情報.docx");

        //1つ目のセクションを取得する
        Section section = document.getSections().get(0);

        //表のデータを定義する
        String[] header = {"名前", "部門", "给料"};
        String[][] data =
                {
                        new String[]{"Kline", "IT", "¥10,000,000"},
                        new String[]{"Martin", "美術・工芸品", "¥2,000,000"},
                        new String[]{"Mendes", "研究・開発", "¥3,800,000"},
                        new String[]{"Patrick", "IT", "¥28,000,000"},
                        new String[]{"合計", "", "¥43,800,000"},
                };

        //セクションに表を追加する
        Table table = section.addTable(true);

        //表の行と列の数を指定する
        table.resetCells(data.length + 1, header.length);

        //特定のセルを水平に結合する
        table.applyHorizontalMerge(5, 0, 1);

        //表のヘッダー行のデータと書式を設定する
        TableRow row = table.getRows().get(0);
        row.isHeader(true);
        row.setHeight(30);
        row.setHeightType(TableRowHeightType.Exactly);
        row.getRowFormat().setBackColor(new Color(142, 170, 219));
        for (int i = 0; i < header.length; i++) {
            row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
            Paragraph p = row.getCells().get(i).addParagraph();
            p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
            TextRange txtRange = p.appendText(header[i]);
            txtRange.getCharacterFormat().setFontSize(14);
            txtRange.getCharacterFormat().setBold(true);
            txtRange.getCharacterFormat().setTextColor(Color.white);
        }

        //表のデータ行のデータと書式を設定する
        for (int r = 0; r < data.length; r++) {
            TableRow dataRow = table.getRows().get(r + 1);
            dataRow.setHeight(25);
            dataRow.setHeightType(TableRowHeightType.Exactly);
            dataRow.getRowFormat().setBackColor(Color.white);
            for (int c = 0; c < data[r].length; c++) {
                dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
                dataRow.getCells().get(c).addParagraph().appendText(data[r][c]);
            }
        }

        //表の特定行の背景色を設定する
        for (int j = 1; j < table.getRows().getCount(); j++) {
            if (j % 2 == 0) {
                TableRow row2 = table.getRows().get(j);
                for (int f = 0; f < row2.getCells().getCount(); f++) {
                    row2.getCells().get(f).getCellFormat().setBackColor(new Color(217, 226, 243));
                }
            }
        }

        //結果文書を保存する
        document.saveToFile("表の作成.docx", FileFormat.Docx);
    }
}

【結果のWord文書】
Word文書に表を作成する

Word文書内の表を読み込む

表のデータを読み取るには、表のすべての行、各行のすべてのセル、各セルのすべての段落をループして、各段落からデータを取り出してテキストファイルに保存する必要があります。詳しい手順は以下の通りです。

  • Document クラスのインスタンスを作成します。
  • Document.loadFromFile() メソッドを使用して Word 文書を読み込みます。
  • Document.getSections().get(int) メソッドを使用して、特定のセクションをそのインデックスで取得します。
  • Section.getTables().get(int) メソッドを使用して、セクション内の特定の表をそのインデックスで取得します。
  • StringBuilder クラスのインスタンスを作成します。
  • 表のすべての行をループ処理します。
  • 各行内のすべてのセルをループ処理します。
  • 各セルにあるすべての段落をループ処理します。
  • Paragraph.getText() メソッドを使用して各段落からテキストを取得し、その結果をStringBuilderに保存します。
  • StringBuilder のテキストをテキストファイルに書き出します。

Java

import com.spire.doc.Document;
import com.spire.doc.Section;
import com.spire.doc.TableCell;
import com.spire.doc.TableRow;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.interfaces.ITable;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class readTableData {
    public static void main(String []args) throws IOException {
        //Document クラスのインスタンスを作成する
        Document document = new Document();
        //Word文書を読み込む
        document.loadFromFile("表の作成.docx");

        //1つ目のセクションを取得する
        Section section = document.getSections().get(0);

        //1つ目のセクションにある1つ目の表を取得する
        ITable table = section.getTables().get(0);

        //StringBuilder クラスのインスタンスを作成する
        StringBuilder sb = new StringBuilder();

        //テーブルのすべての行をループする
        for (int i = 0; i < table.getRows().getCount(); i++) {
            TableRow row = table.getRows().get(i);
            //各行内のすべてのセルをループ処理する
            for (int j = 0; j < row.getCells().getCount(); j++) {
                TableCell cell = row.getCells().get(j);
                //各セルのすべての段落をループで処理する
                for (int k = 0; k < cell.getParagraphs().getCount(); k++) {
                    //各段落からテキストを抽出する
                    Paragraph paragraph = cell.getParagraphs().get(k);
                    String text = paragraph.getText();
                    //StringBuilderにテキストを追加する
                    sb.append(text+ "    ");
                }
            }
            sb.append("\r\n");
        }

        //StringBuilderのテキストをtxtファイルに保存する
        File file = new File("表のデータ.txt");
        if (file.exists())
        {
            file.delete();
        }
        FileWriter fWriter = new FileWriter("表のデータ.txt", true);
        try {
            fWriter.write(sb.toString());
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fWriter.flush();
                fWriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

【結果のWord文書】
Word文書内の表を読み込む

Free Spire.Doc for Javaを使って、Word文書に表を追加したり、Word文書からデータを抽出したりする方法を紹介します。また、その他にもWord文書を扱う様々な機能を備えています。Free Spire.Doc for Javaについてもっと知りたい方は、Spire.Doc Forumにアクセスしてください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0