This simple tutorial will elaborate how to adjust column width in Excel using Java. We can have a variety of data in Excel that may have different lengths and require adjusting the column size to display it properly. You will learn this process to resize columns in Excel using Java here and save the output file as XLSX with the help of step-by-step instructions and a ready-to-run Java code.
Steps to Adjust Column Width in Excel using Java
- Using the Maven repository, add the reference to Aspose.Cells library in the application
- Load the Excel file into the Workbook object whose columns are to be resized
- Access the desired worksheet reference from the collection of worksheets in the workbook
- Get a reference to the Cells collection from the worksheet to set the individual column size
- Set width of a particular column by providing column number and required width
- Using the worksheet object directly, autofit a particular or multiple columns based on contents size
- Save the updated Excel file with resized columns
Here we have seen that to modify Excel column width using Java, we load the target Excel file and then access the desired sheet in it. If you want to set the column width with a fixed value, you may use the Cells collection in the worksheet and if want to autofit the width based on the contents in each cell, you may use autoFitColumn() and autoFitColumns() functions in the worksheet class.
Code to Set Width of Column in Excel using Java
This brief code demonstrates the process to change the width by using the Cells.setColumnWidth() function and providing the column index and a double value describing the exact width. Similarly, for changing the single column size based on the contents, you may call Worksheet.autoFitColumn() by providing the column number. To set the width of multiple columns in a sheet call Worksheet.autoFitColumns() along with the start and end column number.
This easy tutorial has explained how to change the width of a column in excel using java. If you want to learn other features of this product, like saving the output file as PDF, refer to the article on How to Generate PDF from Excel in Java.