Pages Navigation Menu

Coding is much easier than you think

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

 
This was the reports created by my java application and it turned out to be quite irritating as the columns are not auto sized.
 

 
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.

 

4 Comments

  1. thank!! its worked!!

  2. this didnt workk\

  3. you can find some more details in the below link,”http://javadomain.in/excel-columns-expand-using-poi/”

    • alli no hay nada