業務で複数のExcelファイルを受け取り、それらを1つの帳票としてまとめる作業を自動化したいという場面はよくあります。
この記事では、JavaとApache POIライブラリを使って、複数のExcelブックを1つのシートにマージする方法を解説します。
事前準備
必要なライブラリ
Excel操作にはApache POIライブラリを使用します。Mavenを使っている場合は、以下の依存関係をpom.xml
に追加してください。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
対象とするExcelファイル
今回は以下のような複数のExcelファイル(.xlsx)を1つにまとめる前提です。
- ファイル形式:.xlsx(Excel 2007以降)
- 各ファイルの1シート目を対象とする
- すべてのファイルは同じ形式(列構成)
Javaコード:Excelブックのマージ処理
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.nio.file.*;
import java.util.*;
public class ExcelMerger {
public static void main(String[] args) throws IOException {
String inputDir = "input_excels"; // Excelファイルのあるフォルダ
String outputFilePath = "merged_output.xlsx";
Workbook outputWorkbook = new XSSFWorkbook();
Sheet outputSheet = outputWorkbook.createSheet("まとめシート");
int outputRowNum = 0;
// フォルダ内のxlsxファイルをすべて取得
try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(inputDir), "*.xlsx")) {
for (Path path : stream) {
try (InputStream is = Files.newInputStream(path);
Workbook inputWorkbook = new XSSFWorkbook(is)) {
Sheet inputSheet = inputWorkbook.getSheetAt(0);
for (Row inputRow : inputSheet) {
Row outputRow = outputSheet.createRow(outputRowNum++);
for (int cn = 0; cn < inputRow.getLastCellNum(); cn++) {
Cell inputCell = inputRow.getCell(cn);
Cell outputCell = outputRow.createCell(cn);
if (inputCell != null) {
switch (inputCell.getCellType()) {
case STRING:
outputCell.setCellValue(inputCell.getStringCellValue());
break;
case NUMERIC:
outputCell.setCellValue(inputCell.getNumericCellValue());
break;
case BOOLEAN:
outputCell.setCellValue(inputCell.getBooleanCellValue());
break;
case FORMULA:
outputCell.setCellFormula(inputCell.getCellFormula());
break;
default:
outputCell.setCellValue("");
}
}
}
}
}
}
}
// マージした内容をファイル出力
try (OutputStream os = new FileOutputStream(outputFilePath)) {
outputWorkbook.write(os);
}
outputWorkbook.close();
System.out.println("Excelマージ完了: " + outputFilePath);
}
}
コードのポイント解説
- DirectoryStream を使って、フォルダ内の`.xlsx`ファイルを一括取得。
- 各Excelファイルの最初のシート(
getSheetAt(0)
)を対象に読み込み。 - 1行ずつ読み込んで、マージ先のブックにコピー。
- セルの型に応じて値を個別に設定(
switch
文を使用)。
実行結果イメージ
以下のように、複数のExcelファイルのデータが1つのシートに順番に追加されていきます。
社員ID | 名前 | 部署 |
---|---|---|
101 | 田中 太郎 | 営業部 |
102 | 山田 花子 | 経理部 |
103 | 佐藤 一郎 | 技術部 |
注意点
- Excelファイルのレイアウトが揃っていない場合はエラーになる可能性があるため、事前に確認が必要です。
- 1つのファイルが非常に大きい場合は、
SXSSFWorkbook
などメモリ節約型のAPIを検討してください。
まとめ
JavaとApache POIを使えば、複数のExcelファイルを簡単に1つの帳票としてまとめることができます。
日々の定型業務を効率化したい方は、ぜひこの方法を活用してみてください。