Apache POI – JavaでExcelファイルを読み書きする
この記事では、Apache POIを使用してExcelファイルを読み書きする方法について説明します。
1. Apache POIライブラリの基本的な定義
このセクションでは、Excelの読み取りおよび書き込み中に使用される基本クラスについて簡単に説明します。
-
HSSFは、Microsoft Excel 2003ファイルに関連する操作を示すために、クラス名の前にプレフィックスが付けられます。 -
XSSFは、Microsoft Excel 2007ファイル以降に関連する操作を示すために、クラス名の前に接頭辞が付けられます。 -
XSSFWorkbookおよびHSSFWorkbookは、Excelワークブックとして機能するクラスです。 -
HSSFSheetおよびXSSFSheetは、Excelワークシートとして機能するクラスです。 -
RowはExcel行を定義します -
Cellは、行を参照してアドレス指定されたExcelセルを定義します。
2. Apache POIをダウンロードする
Apache POIライブラリは、Maven依存関係を使用して簡単に利用できます。
pom.xml
org.apache.poi poi-ooxml 3.15
3. Apache POIライブラリ–簡単なExcelの作成
以下のコードは、Apache POIライブラリを使用して簡単なExcelファイルを作成する方法を示しています。 コードは、2次元データ配列を使用してデータを保持します。 データはXSSFWorkbookオブジェクトに書き込まれます。 XSSFSheetは、作業中のワークシートです。 コードは次のとおりです。
ApachePOIExcelWrite.java
package com.techfou;
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;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ApachePOIExcelWrite {
private static final String FILE_NAME = "/tmp/MyFirstExcel.xlsx";
public static void main(String[] args) {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Datatypes in Java");
Object[][] datatypes = {
{"Datatype", "Type", "Size(in bytes)"},
{"int", "Primitive", 2},
{"float", "Primitive", 4},
{"double", "Primitive", 8},
{"char", "Primitive", 1},
{"String", "Non-Primitive", "No fixed size"}
};
int rowNum = 0;
System.out.println("Creating excel");
for (Object[] datatype : datatypes) {
Row row = sheet.createRow(rowNum++);
int colNum = 0;
for (Object field : datatype) {
Cell cell = row.createCell(colNum++);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
try {
FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
workbook.write(outputStream);
workbook.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
上記のコードを実行すると、出力として次の結果が得られます。

4. Apache POIライブラリ– Excelファイルの読み取り
以下のコードは、Apache POIライブラリを使用してExcelファイルを読み取る方法を説明しています。 関数getCellTypeEnumはバージョン3.15で非推奨になり、バージョン4.0以降はgetCellTypeに名前が変更されます。
ApachePOIExcelRead.java
package com.techfou;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
public class ApachePOIExcelRead {
private static final String FILE_NAME = "/tmp/MyFirstExcel.xlsx";
public static void main(String[] args) {
try {
FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator| cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
//getCellTypeEnum shown as deprecated for version 3.15
//getCellTypeEnum ill be renamed to getCellType starting from version 4.0
if (currentCell.getCellTypeEnum() == CellType.STRING) {
System.out.print(currentCell.getStringCellValue() + "--");
} else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) {
System.out.print(currentCell.getNumericCellValue() + "--");
}
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
上記のコードを実行すると、次の出力が得られます。
Datatype--Type--Size(in bytes)-- int--Primitive--2.0-- float--Primitive--4.0-- double--Primitive--8.0-- char--Primitive--1.0-- String--Non-Primitive--No fixed size--