如何从 xlsx 文件中读取值以通过 getter 和 setter 将值存储到对象,最后存储到数组列表

how to read values from xlsx file to store value through getter and setter to object and finally to array list

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

 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());
           }

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);
                      }
                  }
              }