Pages Navigation Menu

Coding is much easier than you think

Java code to Auto size columns in Excel files created with Apache POI

Posted by on Sep 9, 2012 in Java, Java Excel | 4 comments

This was the reports created by my java application and it turned out to be quite irritating as the columns are not auto sized.
input xls
The solution to the above problem is you just need to call a method to auto fit the column width.
Here is the code to auto size the first 5 columns of the spread sheet.

	HSSFSheet sheet = workBook.createSheet("testXls");
	// Code to Auto size the column widths
	for(int columnPosition = 0; columnPosition< 5; columnPosition++) {
             sheet.autoSizeColumn((short) (columnPosition));


Recommended reading:

After using the above code the following output is obtained.
output xls

Note: The method autoSizeColumn() should be called only when the content are written into the excel file.


Read More