Total Pageviews

2013/11/15

How to adjust column width to fit the contents in Apache POI

Problem
I utilized Apache POI to write data into excel file. But I found out each cell width has the same default width, it does not adjust it's width based on its contents.

Solution
You can call autoSizeColumn method in HSSFSheet to fix this problem.
Here is the JavaDoc: http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFSheet.html#autoSizeColumn(int, boolean)
If you have 10 columns, you need to call autoSizeColumn 10 times in for-loop.
For example.
1:          for (int resizeCnt = 0; resizeCnt < pdateSet.size() + 3; resizeCnt++) {  
2:            sheet.autoSizeColumn(resizeCnt);  
3:          }  
Check the result after we call autoSizeColumn. 
You can see some columns' width may not really fit the contents, but it's much better than the original one.

No comments: