0
0

More than 1 year has passed since last update.

Apache POIを使って、シートをソートしたい

Last updated at Posted at 2021-10-31

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>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0