
Microsoft Excel includes a built‑in AutoFit feature that automatically resizes rows and columns based on the length of the cell content. When you generate or modify Excel workbooks programmatically, you often need to apply this behavior on the fly. This article explains how to autofit rows and columns in Excel files using Java, with clear code examples for both row height and column width adjustments.
- Java API to AutoFit Rows and Columns in Excel
- AutoFit Rows in Excel in Java
- AutoFit Columns in Excel in Java
AutoFit Excel Rows and Columns - Java API
Aspose.Cells for Java offers a comprehensive set of classes for creating, editing, and converting spreadsheets. Its high‑performance engine makes it easy to implement both basic and advanced Excel features, including AutoFit for rows and columns. You can obtain the library by downloading the JAR file or by adding the Maven dependency shown below.
Repository:
<repository>
<id>AsposeJavaAPI</id>
<name>Aspose Java API</name>
<url>https://repository.aspose.com/repo/</url>
</repository>
Dependency:
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-cells</artifactId>
<version>22.8</version>
</dependency>
AutoFit Rows in Excel in Java
To AutoFit a row, first load the workbook, locate the target worksheet, and then call the autoFitRow method with the row index. Finally, save the workbook to persist the changes.
- Load the Excel file using Workbook class.
- Retrieve the required worksheet with Workbook.getWorksheets().get(index).
- Apply AutoFit to a specific row using Worksheet.autoFitRow(rowIndex).
- Save the updated workbook with Workbook.save().
The sample below demonstrates how to AutoFit a single row in Java.
Java AutoFit Columns in Excel
AutoFitting a column follows the same workflow as rows; the only difference is the method used to adjust the column width. Use autoFitColumn with the column index to resize the column automatically.
- Load the Excel file using Workbook class.
- Access the target worksheet via Workbook.getWorksheets().get(index).
- AutoFit the desired column with Worksheet.autoFitColumn(columnIndex).
- Save the workbook using Workbook.save().
The following code snippet shows how to AutoFit a column in Java.
Java API to AutoFit Excel Rows and Columns - Get a Free License
You can get a free temporary license to use the AutoFit functionality without evaluation restrictions.
Conclusion
This guide covered the steps required to AutoFit rows and columns in Excel workbooks using Aspose.Cells for Java. By loading a workbook, selecting the appropriate worksheet, and invoking autoFitRow or autoFitColumn, you can programmatically ensure that cell content is displayed optimally.
Explore Aspose’ Spreadsheet API for Java
Visit the documentation to discover additional capabilities of Aspose.Cells for Java, and join the conversation on our forum for any questions or feedback.