27
votes

I am beginner to Apache POI api. I am trying to create excel sheet using arraylist.

My java code is as follows.

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

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

1
you are setting the auto column size before the data is being written. Therefore it doesn't know how to size it. Add it after your loopSean
@Sean Very useful explanation for a beginner like me. Thanks!!mvg
@gavenkoa How is the link you provided relevant to the discussion in this page?mvg
@mvg It provides same answer as for your question.gavenkoa

1 Answers

59
votes

You just need to move the call to

sheet.autoSizeColumn(5);

to a point in your code after the data has been added, so right after your while loop should work.