LoginSignup
1
1

More than 1 year has passed since last update.

Apache POIを使って列の幅の自動調整を行う

Posted at

Excelの列の幅の自動調整に相当することをApache POIで実現したい場合、Sheet.autoSizeColumnを利用すると良いです。ただし、とくに日本語が混ざっている場合、Sheet.autoSizeColumnがうまく列の幅を調整してくれないことがあります。これを回避したい場合、自動調整したい列のセルのフォントを日本語対応のものに設定してやると、想定通り動くようです。

以下はそのサンプルになります。

Workbook workbook = ...;
Sheet sheet = ...;

// 幅の自動調整をしたい列のセルのフォントを日本語対応のものに設定する。
// (ここでは例としてYu Gothic UIを使う)
Cell cell = ...;
CellStyle cellStyle = workbook.createCellStyle();
Font font = workbook.createFont();
font.setFontName("Yu Gothic UI");
cellStyle.setFont(font);
cell.setCellStyle(cellStyle);

// 幅の自動調整を行う (ここでは例としてB列とする)
CellReference cellReference = new CellReference("B");
sheet.autoSizeColumn(cellReference.getCol());

環境情報: pom.xml抜粋

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.target>11</maven.compiler.target>
    <maven.compiler.source>11</maven.compiler.source>
</properties>

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>
1
1
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
1
1