Java 使用apache poi时excel单元格大小适配内容大小的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4015623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Problem in fitting the excel cell size to the size of the content when using apache poi
提问by mvg
I am beginner to Apache POI api. I am trying to create excel sheet using arraylist.
我是 Apache POI api 的初学者。我正在尝试使用 arraylist 创建 excel 表。
My java code is as follows.
我的java代码如下。
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFCellStyle style = wb.createCellStyle();
style.setFillForegroundColor(HSSFColor.LIME.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
HSSFRow row4 = sheet.createRow(4);
row4.createCell(4).setCellValue("name");
row4.createCell(5).setCellValue("emailId");
sheet.autoSizeColumn(5);
List<Bean> nameList = this.getArrayList();
Iterator<Bean> nameListIterator = nameList.iterator();
sheet.autoSizeColumn(5);
int i=5;
HSSFRow row = null;
while(nameListIterator.hasNext())
{
Bean bean = nameListIterator.next();
row = sheet.createRow(i);
row.createCell(4).setCellValue(bean.getName());
row.createCell(5).setCellValue(bean.getMailId());
i++;
}
The arraylist is as follows:
数组列表如下:
List<Bean> beanList = new ArrayList<Bean>();
beanList.add(new Bean("Amy","[email protected]"));
beanList.add(new Bean("Joan","[email protected]"));
beanList.add(new Bean("Megan","[email protected]"));
beanList.add(new Bean("Joe","[email protected]"));
beanList.add(new Bean("Febi","[email protected]"));
When the excel sheet is generated, the column does not fit to the size of the content correctly. I searched Google related to this problem and found
生成excel表格时,列不适合内容的大小。我搜索了与此问题相关的 Google 并找到了
sheet.autoSizeColumn(5);
sheet.autoSizeColumn(5);
is the solution to my problem. I added as in the code above, but still the problem persists. Am I using it correctly?
是我的问题的解决方案。我在上面的代码中添加了,但问题仍然存在。我是否正确使用它?
Is there any other solution?
还有其他解决方案吗?
Please help
请帮忙
Thanks in advance
提前致谢
P.s: I am using Apache Poi 3.6
Ps:我使用的是 Apache Poi 3.6
采纳答案by Bill the Lizard
You just need to move the call to
您只需要将呼叫移至
sheet.autoSizeColumn(5);
to a point in your code afterthe data has been added, so right after your while loop should work.
添加数据后到代码中的某个点,因此在您的 while 循环之后应该可以正常工作。