Write data into Excel sheet java

非 Y 不嫁゛ 提交于 2019-12-08 02:20:27

问题


I have 3 lists namely list1, list2 and list3. And I want to display these lists in an excel sheet as 3 columns. For example the values in list 1 should be displayed in the first column of Excel sheet. I am adding all the 3 lists to a final list as below and able to display them as separate rows and no idea how can i display as columns. I am using apachepoi.

List<List> finalList = new ArrayList<List>();
     finalList .add(list1);
     finalList .add(list2);
 WritingToExcelFile(List<List> l1) throws Exception {  //passing finalList here
    try {
        for (int j = 0; j < l1.size(); j++) {
            Row row = firstSheet.createRow(rownum);
            List<String> l2 = l1.get(j);
            for (int k = 0; k < l2.size(); k++) {
                Cell cell = row.createCell(k);
                cell.setCellValue(l2.get(k));
            }
            rownum++;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
    }
}

回答1:


Assuming your lists are all the same size, why not something like:

Sheet s = wb.createSheet();
for (int i=0; i<firstList.size(); i++) {
   Row r = s.createRow(i);
   r.createCell(0).setCellValue( list1.get(i) );
   r.createCell(1).setCellValue( list2.get(i) );
   r.createCell(2).setCellValue( list3.get(i) );
}

Add extra error handling if your lists might not be the same length, and extra logic if you need to do formatting / dates / etc for the list contents



来源:https://stackoverflow.com/questions/19361115/write-data-into-excel-sheet-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!