Java: AutoFit Column Width and Row Height in Excel

AutoFit is a very practical feature MS Excel offers to automatically resize cells to accommodate different sized data. With a single click, it makes all the data in a cell clearly visible without having to manually adjust the column width or row height. In this article, you will learn how to programmatically AutoFit the column width and row height in an Excel worksheet using Spire.XLS for Java.

Install Spire.XLS for Java

First, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls</artifactId>
        <version>14.4.4</version>
    </dependency>
</dependencies>
    

AutoFit Column Width and Row Height in Excel

The detailed steps are as follows.

  • Create a Workbook object.
  • Load a sample Excel document using Workbook.loadFromFile() method.
  • Get a specified worksheet using Workbook.getWorksheets().get() method.
  • Get the used range on the specified worksheet using Worksheet.getAllocatedRange() method.
  • Autofit column width and row height in the range using CellRange.autoFitColumns() and CellRange.autoFitRows() methods.
  • Save the document to another file using Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;

public class AutoFitColumn {
    public static void main(String[] args) {
        //Create a Workbook object
        Workbook workbook = new Workbook();

        //Load a sample Excel document
        workbook.loadFromFile("E:\\Files\\Test.xlsx");

        //Get the first worksheet
        Worksheet worksheet = workbook.getWorksheets().get(0);

        //AutoFit column width and row height
        worksheet.getAllocatedRange().autoFitColumns();
        worksheet.getAllocatedRange().autoFitRows();

        //Save the document
        workbook.saveToFile("AutoFitCell.xlsx", ExcelVersion.Version2013);
    }
}

Java: AutoFit Column Width and Row Height in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.