0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaでWord文書から表データを抽出する方法

Last updated at Posted at 2025-01-24

Word 文書は広く使用されているファイル形式の一つであり、財務報告書、プロジェクト計画、実験データ記録など、さまざまな分野にわたる豊富な表形式データを含むことがよくあります。これらの表形式データを抽出することで、データ分析やコンテンツの再作成が容易になり、多くの場面で役立ちます。Java を使用して Word 文書の表形式データを抽出することで、データ処理の一貫性と正確性を確保し、作業にかかる時間とコストを大幅に削減することが可能です。本記事では、Java を使用して Word 文書内の表形式データを抽出する方法を紹介します。

  • JavaでWord文書のテーブルをテキストファイルに抽出
  • JavaでWord文書のテーブルをExcelファイルに抽出

本記事で紹介する方法では、無料のFree Spire.Doc for Javaを使用します。Maven の設定例は以下の通りです:

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

JavaでWord文書のテーブルをテキストファイルに抽出

Section.getTables() メソッドを使用して、Word 文書の各セクションから表を取得し、表の行や列を順次処理することで、表内の段落テキストを抽出できます。以下に具体的な手順を示します:

  1. Document オブジェクトを作成し、ファイルから Word 文書を読み込む。
  2. 文書内の各セクションを順に処理し、Section.getTables() で表を取得する。
  3. 各表の行とセルを順に処理し、テキスト内容を抽出する。
  4. 抽出したテキストを StringBuilder に追加する。
  5. StringBuilder 内の内容を出力または保存する。

コード例:

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;

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

public class ExtractWordTable {
    public static void main(String[] args) {
        // Document オブジェクトを作成
        Document doc = new Document();

        try {
            // Word 文書を読み込む
            doc.loadFromFile("GSample.docx");

            // 各セクションを処理
            for (int i = 0; i < doc.getSections().getCount(); i++) {
                Section section = doc.getSections().get(i);
                for (int j = 0; j < section.getTables().getCount(); j++) {
                    Table table = section.getTables().get(j);
                    StringBuilder tableText = new StringBuilder();
                    for (int k = 0; k < table.getRows().getCount(); k++) {
                        TableRow row = table.getRows().get(k);
                        StringBuilder rowText = new StringBuilder();
                        for (int l = 0; l < row.getCells().getCount(); l++) {
                            TableCell cell = row.getCells().get(l);
                            String cellText = "";
                            for (int m = 0; m < cell.getParagraphs().getCount(); m++) {
                                Paragraph paragraph = cell.getParagraphs().get(m);
                                cellText += paragraph.getText() + " ";
                            }
                            if (l < row.getCells().getCount() - 1) {
                                rowText.append(cellText).append("\t");
                            } else {
                                rowText.append(cellText).append("\n");
                            }
                        }
                        tableText.append(rowText);
                    }
                    try (FileWriter writer = new FileWriter("output/Tables/Section-" + (i + 1) + "-Table-" + (j + 1) + ".txt")) {
                        writer.write(tableText.toString());
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

結果:
2025-01-24_165807.png

JavaでWord文書のテーブルをExcelファイルに抽出

Free Spire.XLS for Java を使用することで、抽出した表データを直接 Excel ワークシートに書き込むことが可能です。以下に具体的な手順を示します:

  1. DocumentWorkbook オブジェクトを作成し、Workbook のデフォルトシートを削除する。
  2. Word 文書を Document に読み込み、セクションと表を順次処理する。
  3. 各表に対して、Workbook.getWorksheets().add() を使用して新しいワークシートを作成する。
  4. 表の行とセルを順に処理し、テキスト内容を抽出する。
  5. Worksheet.getRange().get().setValue() を使用して抽出したテキストをワークシートの対応するセルに書き込み、書式を設定する。
  6. Workbook を Excel ファイルとして保存する。

コード例:

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class ExtractWordTableToExcel {
    public static void main(String[] args) {
        Document doc = new Document();
        Workbook workbook = new Workbook();
        workbook.getWorksheets().clear();

        try {
            doc.loadFromFile("Sample.docx");

            for (int i = 0; i < doc.getSections().getCount(); i++) {
                Section section = doc.getSections().get(i);
                for (int j = 0; j < section.getTables().getCount(); j++) {
                    Table table = section.getTables().get(j);
                    Worksheet sheet = workbook.getWorksheets().add("Section-" + (i + 1) + "-Table-" + (j + 1));
                    for (int k = 0; k < table.getRows().getCount(); k++) {
                        TableRow row = table.getRows().get(k);
                        for (int l = 0; l < row.getCells().getCount(); l++) {
                            TableCell cell = row.getCells().get(l);
                            String cellText = "";
                            for (int m = 0; m < cell.getParagraphs().getCount(); m++) {
                                Paragraph paragraph = cell.getParagraphs().get(m);
                                cellText += (m > 0 && m < cell.getParagraphs().getCount() - 1) ? paragraph.getText() + "\n" : paragraph.getText();
                                sheet.getRange().get(k + 1, l + 1).setValue(cellText);
                            }
                            sheet.autoFitColumn(l + 1);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        workbook.saveToFile("output/WordTableToExcel.xlsx", FileFormat.Version2016);
        workbook.dispose();
    }
}

結果:
2025-01-24_170514.png

本記事では、Java を使用して Word 文書内の表形式データを抽出する方法を、手順とコード例を交えて解説しました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?