2010-10-25 47 views
22

我是Apache POI api的初學者。我正在嘗試使用數組列表創建Excel表。在使用apache poi時,將excel單元格大小與內容大小相匹配的問題

我的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++; 
    } 

該ArrayList如下:

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]")); 

當產生excel表中,列不適合於內容的大小正確。我搜索了谷歌相關的這個問題,發現

sheet.autoSizeColumn(5);

是我的問題的解決方案。我添加了上面的代碼,但仍然存在問題。我是否正確使用它?

有沒有其他解決方案?

請幫

在此先感謝

PS:我使用的Apache POI 3.6

+3

您正在設置數據寫入前的自動列大小。因此它不知道如何確定它的大小。在你的循環之後添加它 – Sean 2010-10-25 15:04:49

+0

@Sean對於像我這樣的初學者來說非常有用的解釋。謝謝!! – mvg 2010-10-26 05:15:18

+0

http://stackoverflow.com/questions/20190317/apache-poi-excel-big-auto-column-width – gavenkoa 2014-02-07 11:06:55

回答

51

您只需將呼叫轉移到

sheet.autoSizeColumn(5); 

到一個點在你的代碼之後數據已被添加,因此您的while循環之後應該正常工作。

+1

謝謝你的回答。你的回答解決了我的問題。我剛剛在while循環之後移動了autosizecolumn調用,現在它工作。再次感謝。 – mvg 2010-10-26 05:14:48