0

我试图从 excel 文件中读取值,以将 XSSFWorkbook 中的每一行和单元格存储在一个对象中,并将其添加到 arraylist。但它只添加了 arraylist 中的最后一个元素。包括我下面的代码。

 try 
           {  
               ArrayList<OrderInfo> orderList = new ArrayList<OrderInfo>();
               XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream("C:/mytemp/Order Details.xlsx"));

               for (Sheet sheet : wb ) {
                   OrderInfo order_Info = new OrderInfo();
                      for (Row row : sheet) {
                          int rowId = row.getRowNum();
                          if(rowId != 0){
                               Cell del_zone = row.getCell(0);
                               order_Info.setDel_zone(del_zone.getStringCellValue());
                               Cell cust_id = row.getCell(1);
                               order_Info.setCustomer_id(cust_id.getStringCellValue());
                          }
                      }
                      orderList.add(order_Info);
                  }

                  for(int i = 0;i<orderList.size();i++){
                   logger.info("*******Print List Object******"+orderList.get(i).getDel_zone()+"****Cust_Id****"+orderList.get(i).getCustomer_id());
                  }

               }
           catch (Exception e) 
           {
                   System.err.println("Exception :" + e.getMessage());
           }
4

1 回答 1

2

orderList.add(order_Info)应该在for (Row row : sheet)循环内,你在外面

它还需要在循环内创建:OrderInfo order_Info = new OrderInfo();应该稍后

           for (Sheet sheet : wb ) {
                  for (Row row : sheet) {
                      int rowId = row.getRowNum();
                      if(rowId != 0){
                           Cell del_zone = row.getCell(0);
                           OrderInfo order_Info = new OrderInfo();
                           order_Info.setDel_zone(del_zone.getStringCellValue());
                           Cell cust_id = row.getCell(1);
                           order_Info.setCustomer_id(cust_id.getStringCellValue());
                           orderList.add(order_Info);
                      }
                  }
              }
于 2017-03-17T13:40:37.073 回答