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ファイルをダウンロードします。

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

Apache POI Jar ファイルを Java クラスパスに追加する
注意: 他のファイルと共にlibとooxml-libからのファイルもコピーします。
POIのクラスとインターフェース
以下は、Javaで使用できるXLSおよびXLSXファイル形式をサポートするクラスです:

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で読みます。

読み取られるExcelファイル
JavaでExcelファイルを読む手順
- 任意のJava IDEを使用してJavaプロジェクトを作成します。このプロジェクトにはNetBeansを使用します。
- 次に、プロジェクトに
libフォルダを作成します。 - その後、前のステップで作成した
libフォルダにダウンロードしたJARファイルを追加します。 Class-Pathを設定するには、プロジェクトフォルダを右クリック > ビルドパス > 外部JARファイルを追加 > 上記のすべてのJARファイルを選択 > 適用して閉じる。- 次に、ReadExcelFileDemoという名前のクラスファイルを作成します。
- 名前"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();
}
}出力:
Id Names
1 Zeeshan
2 Shoaib
3 Umar
4 Rizwan
5 AhsanId Names
1 Zeeshan
2 Shoaib
3 Umar
4 Rizwan
5 Ahsan次の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();
}
}
}出力:
Id Names
1 Zeeshan
2 Shoaib
3 Umar
4 Rizwan
5 AhsanId Names
1 Zeeshan
2 Shoaib
3 Umar
4 Rizwan
5 AhsanThe 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);
}
}
}IronXLを使用することで、開発者の作業が大幅に簡単になります。 そのシンプルで使いやすいコードは、Excelファイルを扱う際にソフトウェアがバグを起こしにくくします。
IronXLをダウンロードして、今すぐプロジェクトで使い始めましょう。








