Excelにはシートをソートする機能は標準で用意されていません。通常はVBAを利用するのですが、VBAにはソート関数がなく、これを自前を用意するのは面倒。そもそもVBAが苦手ということもあり、JavaとApache POIで処理したことがこの記事を書いたきっかけになります。
前置きはさておき、以下は「src.xlsxのシートをシート名でソートしたものをdst.xlsxに書き出す」というものです。
try (Workbook srcWorkBook = WorkbookFactory.create(Files.newInputStream(Paths.get("src.xlsx")));
OutputStream dstWorkBook = Files.newOutputStream(Paths.get("dst.xlsx"))) {
List<String> sheetNames = new ArrayList<>();
for (Sheet sheet : srcWorkBook) {
sheetNames.add(sheet.getSheetName());
}
Collections.sort(sheetNames);
for (int i = 0, len = sheetNames.size(); i < len; i++) {
srcWorkBook.setSheetOrder(sheetNames.get(i), i);
}
srcWorkBook.write(dstWorkBook);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
環境情報 (pom.xmlの抜粋)
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.0.0</version>
</dependency>