フッターコンテンツにスキップ
EXCEL ツール

JavaでExcelファイルを読み取る方法(チュートリアル)

Excelとは何ですか?

Microsoft Excelワークブックは、ユーザーがデータを効率的に整理および保存するためのスプレッドシートベースのソフトウェアです。 データを行と列を使用して表形式で保存および整理します。 Excelスプレッドシートのセルはデータを保持するボックスであり、さまざまなスタイル、書式、数式で操作できます。

JavaでExcelファイルを読む方法?

Excelファイルを読むことは時々複雑です。 JavaでExcelファイルを読むことは、Excelのセルのため、JavaでWordファイルを読むこととは少し異なります。 JDKはMicrosoft Excelドキュメントを読み書きするための直接的なAPIを提供していません。 その代わりに、サードパーティライブラリApache POIに依存しなければなりません。

Apache POIライブラリ

POIは「Poor Obfuscation Implementation」の頭字語です。Apache POIは、Microsoftドキュメントの読み書きを目的としたオープンソースのJavaライブラリです。 Apache POIを使用することで、Microsoft Officeのファイル形式を作成、修正、表示/読み取り操作が可能です。

Apache POIライブラリをダウンロードしてインストールする

最初に、POI JARの最新バージョンをダウンロードします。 http://poi.apache.org/download.htmlに移動し、JavaでExcelファイルを読むJava APIが含まれる最新のZIPファイルをダウンロードします。

class="content-img-align-center">
class="center-image-wrapper"> JavaでExcelファイルを読む方法、図1:バイナリ配布ファイルをダウンロード

class="content__image-caption">Apache POI JARファイルをダウンロード

ZIPファイルをダウンロードしたら、解凍してプロジェクトのクラスパスに以下のJARファイルを追加する必要があります。 これはExcelファイルから読むで説明されています。

class="content-img-align-center">
class="center-image-wrapper"> JavaでExcelファイルを読む方法、図2:JARファイル

class="content__image-caption">JavaクラスパスにApache POI JARファイルを追加

注意: 他のファイルと共にlibooxml-libからのファイルもコピーします。

POIのクラスとインターフェース

以下は、Javaで使用できるXLSおよびXLSXファイル形式をサポートするクラスです:

class="content-img-align-center">
class="center-image-wrapper"> JavaでExcelファイルを読む方法、図3:Apache POIクラス

class="content__image-caption">Apache POIクラス

以下は、JavaでXLSおよびXLSXファイルを読むためのPOIのさまざまなJavaインターフェースとクラスのリストです:

WorkbookインターフェースはHSSFWorkbookおよびXSSFWorkbookクラスによって実装されています:

  • HSSFWorkbook: これはXLSファイルのクラス表現です。
  • XSSFWorkbook: これはXLSXファイルのクラス表現です。

SheetインターフェースはHSSFSheetおよびXSSFSheetクラスによって実装されています:

  • HSSFSheet: これはXLSファイル内のシートを表すクラスです。
  • XSSFSheet: これはXLSXファイル内のシートを表すクラスです。

RowインターフェースはHSSFRowおよびXSSFRowクラスによって実装されています:

  • HSSFRow: これはXLSファイルのシート内の行を表すクラスです。
  • XSSFRow: これはXLSXファイルのシート内の行を表すクラスです。

CellインターフェースはHSSFCellおよびXSSFCellクラスによって実装されています:

  • HSSFCell: これはXLSファイルの行のセルを表すクラスです。
  • XSSFCell: これはXLSXファイルの行のセルを表すクラスです。

Excelファイルから読む

例として、以下のExcelファイルをJavaで読みます。

class="content-img-align-center">
class="center-image-wrapper"> JavaでExcelファイルを読む方法、Figure 4: 読むExcelファイル

class="content__image-caption">読むExcelファイル

JavaでExcelファイルを読む手順

  1. 任意のJava IDEを使用してJavaプロジェクトを作成します。このプロジェクトにはNetBeansを使用します。
  2. 次に、プロジェクトにlibフォルダを作成します。
  3. その後、前のステップで作成したlibフォルダにダウンロードしたJARファイルを追加します。
  4. Class-Pathを設定するには、プロジェクトフォルダを右クリック > ビルドパス > 外部JARファイルを追加 > 上記のすべてのJARファイルを選択 > 適用して閉じる。
  5. 次に、ReadExcelFileDemoという名前のクラスファイルを作成します。
  6. 名前「studentdata.xls」でExcelファイルを作成し、上記のデータまたは任意のデータを書き込んでください。

以下はJavaでExcelファイルを読み込むためのコード例です:

import java.io.File;  
import java.io.FileInputStream;  
import java.io.IOException;  
import org.apache.poi.hssf.usermodel.HSSFSheet;  
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.FormulaEvaluator;  
import org.apache.poi.ss.usermodel.Row;  

public class ReadExcelFileDemo  {  
    public static void main(String[] args) throws IOException {  
        // Obtain input bytes from a file  
        FileInputStream fis = new FileInputStream(new File("C:\\demo\\studentdata.xls"));  

        // Creating workbook instance that refers to .xls file  
        HSSFWorkbook wb = new HSSFWorkbook(fis);   

        // Creating a Sheet object to retrieve the object  
        HSSFSheet sheet = wb.getSheetAt(0);  

        // Evaluating cell type   
        FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();  
        for (Row row : sheet) {  
            for (Cell cell : row) {
                switch (formulaEvaluator.evaluateInCell(cell).getCellType()) {  
                    case NUMERIC: // Field that represents numeric cell type  
                        // Getting the value of the cell as a number  
                        System.out.print(cell.getNumericCellValue() + "\t\t");   
                        break;  
                    case STRING: // Field that represents string cell type  
                        // Getting the value of the cell as a string  
                        System.out.print(cell.getStringCellValue() + "\t\t");  
                        break;
                }
            }
            System.out.println();  
        }

        // Closing the workbook to free resources
        wb.close();
    }
}
import java.io.File;  
import java.io.FileInputStream;  
import java.io.IOException;  
import org.apache.poi.hssf.usermodel.HSSFSheet;  
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.FormulaEvaluator;  
import org.apache.poi.ss.usermodel.Row;  

public class ReadExcelFileDemo  {  
    public static void main(String[] args) throws IOException {  
        // Obtain input bytes from a file  
        FileInputStream fis = new FileInputStream(new File("C:\\demo\\studentdata.xls"));  

        // Creating workbook instance that refers to .xls file  
        HSSFWorkbook wb = new HSSFWorkbook(fis);   

        // Creating a Sheet object to retrieve the object  
        HSSFSheet sheet = wb.getSheetAt(0);  

        // Evaluating cell type   
        FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();  
        for (Row row : sheet) {  
            for (Cell cell : row) {
                switch (formulaEvaluator.evaluateInCell(cell).getCellType()) {  
                    case NUMERIC: // Field that represents numeric cell type  
                        // Getting the value of the cell as a number  
                        System.out.print(cell.getNumericCellValue() + "\t\t");   
                        break;  
                    case STRING: // Field that represents string cell type  
                        // Getting the value of the cell as a string  
                        System.out.print(cell.getStringCellValue() + "\t\t");  
                        break;
                }
            }
            System.out.println();  
        }

        // Closing the workbook to free resources
        wb.close();
    }
}
JAVA

出力:

Id    Names
1     Zeeshan
2     Shoaib
3     Umar
4     Rizwan
5     Ahsan
Id    Names
1     Zeeshan
2     Shoaib
3     Umar
4     Rizwan
5     Ahsan
SHELL

次の2つの主要なポイントを除いて、XLSXファイルを読む手順は同じです:

  • 第一に、ファイル形式を.xlsxに変更します。 「studentdata」という同じファイルを使用できますが、拡張子は.xlsxです。
  • 第二に、Java Apache POIのインポート方法に違いがあります。 コードは次の通りです:
import java.io.File;  
import java.io.FileInputStream;  
import java.util.Iterator;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.Row;  
import org.apache.poi.xssf.usermodel.XSSFSheet;  
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  

public class XLSXReaderExample  {

    public static void main(String[] args) {  
        try {  
            File file = new File("C:\\demo\\studentdata.xlsx");  
            FileInputStream fis = new FileInputStream(file);  

            // Creating Workbook instance that refers to .xlsx file  
            XSSFWorkbook wb = new XSSFWorkbook(fis);   
            XSSFSheet sheet = wb.getSheetAt(0); 

            // Iterating over rows using iterator
            Iterator<Row> itr = sheet.iterator();
            while (itr.hasNext()) {  
                Row row = itr.next();  

                // Iterating over each column in a row
                Iterator<Cell> cellIterator = row.cellIterator();   
                while (cellIterator.hasNext()) {  
                    Cell cell = cellIterator.next();  
                    switch (cell.getCellType()) {  
                        case NUMERIC: // Field that represents numeric cell type  
                            // Getting the value of the cell as a number  
                            System.out.print(cell.getNumericCellValue() + "\t\t");   
                            break;
                        case STRING: // Field that represents string cell type  
                            // Getting the value of the cell as a string  
                            System.out.print(cell.getStringCellValue() + "\t\t");  
                            break;
                    }
                }
                System.out.println("");  
            }  

            // Closing the workbook to free resources
            wb.close();
        } catch (Exception e) {  
            e.printStackTrace();  
        }
    }
}
import java.io.File;  
import java.io.FileInputStream;  
import java.util.Iterator;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.Row;  
import org.apache.poi.xssf.usermodel.XSSFSheet;  
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  

public class XLSXReaderExample  {

    public static void main(String[] args) {  
        try {  
            File file = new File("C:\\demo\\studentdata.xlsx");  
            FileInputStream fis = new FileInputStream(file);  

            // Creating Workbook instance that refers to .xlsx file  
            XSSFWorkbook wb = new XSSFWorkbook(fis);   
            XSSFSheet sheet = wb.getSheetAt(0); 

            // Iterating over rows using iterator
            Iterator<Row> itr = sheet.iterator();
            while (itr.hasNext()) {  
                Row row = itr.next();  

                // Iterating over each column in a row
                Iterator<Cell> cellIterator = row.cellIterator();   
                while (cellIterator.hasNext()) {  
                    Cell cell = cellIterator.next();  
                    switch (cell.getCellType()) {  
                        case NUMERIC: // Field that represents numeric cell type  
                            // Getting the value of the cell as a number  
                            System.out.print(cell.getNumericCellValue() + "\t\t");   
                            break;
                        case STRING: // Field that represents string cell type  
                            // Getting the value of the cell as a string  
                            System.out.print(cell.getStringCellValue() + "\t\t");  
                            break;
                    }
                }
                System.out.println("");  
            }  

            // Closing the workbook to free resources
            wb.close();
        } catch (Exception e) {  
            e.printStackTrace();  
        }
    }
}
JAVA

出力:

Id    Names
1     Zeeshan
2     Shoaib
3     Umar
4     Rizwan
5     Ahsan
Id    Names
1     Zeeshan
2     Shoaib
3     Umar
4     Rizwan
5     Ahsan
SHELL

The IronXL C# ライブラリ

IronXLは、C#でMicrosoft Excelドキュメントを読み取りおよび編集するためのスタンドアロンの.NETライブラリです。 これはMicrosoft Excelのインストールを必要とせず、Interopにも依存しません。

IronXLを使用すると、開発者は数行のコードを書くことで簡単にExcel関連の計算を実行でき、パフォーマンスも高速です。 これにより、2つのセルを加算したり、列の合計を計算したり、Excelテーブルに列全体を追加したり、Excelテーブルに行全体を追加したり、シングルおよびマルチ行の列合計を行うなどのタスクが、IronXLの便利な機能を通じ簡単になります。

IronXLは完全に.NET Framework、.NET Core、モバイル、Xamarin、Azure Linux、およびmacOSをサポートします。

IronXLの機能セット

  • XLS/XLSX/CSV/TSVからの読み込み、データの読み書き編集。
  • XLS/XLSX/CSV/TSV/JSONへの保存とエクスポート。
  • System.Data オブジェクト — ExcelスプレッドシートをSystem.Data.DataSetおよびSystem.Data.DataTableオブジェクトとして操作する。
  • 数式 - Excelの数式を操作。
  • 範囲 — ["A1:B10"] の構文が使いやすい。
  • 並べ替え — 行、列、範囲を並べ替え。
  • スタイリング — 視覚スタイル、フォントとフォントサイズ、背景パターン、ボーダー、配置、数値形式。

以下はC#でIronXLを使用してExcelファイルを読み込むコード例です:

using IronXL;
using System.Linq;

public class ExcelReaderExample
{
    public static void Main(string[] args)
    {
        // Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
        WorkBook workbook = WorkBook.Load("test.xlsx");
        WorkSheet sheet = workbook.WorkSheets.First();

        // Select cells easily in Excel notation and return the calculated value
        int cellValue = sheet["A2"].IntValue;

        // Read from Ranges of cells elegantly
        foreach (var cell in sheet["A2:A10"]) {
            Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
        }
    }
}
using IronXL;
using System.Linq;

public class ExcelReaderExample
{
    public static void Main(string[] args)
    {
        // Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
        WorkBook workbook = WorkBook.Load("test.xlsx");
        WorkSheet sheet = workbook.WorkSheets.First();

        // Select cells easily in Excel notation and return the calculated value
        int cellValue = sheet["A2"].IntValue;

        // Read from Ranges of cells elegantly
        foreach (var cell in sheet["A2:A10"]) {
            Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
        }
    }
}
Imports IronXL
Imports System.Linq

Public Class ExcelReaderExample
	Public Shared Sub Main(ByVal args() As String)
		' Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
		Dim workbook As WorkBook = WorkBook.Load("test.xlsx")
		Dim sheet As WorkSheet = workbook.WorkSheets.First()

		' Select cells easily in Excel notation and return the calculated value
		Dim cellValue As Integer = sheet("A2").IntValue

		' Read from Ranges of cells elegantly
		For Each cell In sheet("A2:A10")
			Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
		Next cell
	End Sub
End Class
$vbLabelText   $csharpLabel

IronXLを使用することで、開発者の作業が大幅に簡単になります。 そのシンプルで使いやすいコードは、Excelファイルを扱う際にソフトウェアがバグを起こしにくくします。

IronXLをダウンロードして、今すぐプロジェクトで使い始めましょう。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。