Pages Navigation Menu

Coding is much easier than you think

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

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.
 
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.

 

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

  • Steve Gates

    thank!! its worked!!

  • jabeen

    this didnt workk\

  • Diva

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

    • Manolilla

      alli no hay nada