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>