2016-06-10 41 views
0

我想讀者使用POI無題頭excel文件,我預期的結果這 expected read excel file讀取Excel與POI文件,而無需頭

這是我的代碼

public String processExcel(Model model, @RequestParam(value = "excelfile", required = false) MultipartFile excelfile, HttpSession session) {   

     try { 
      List<UserRegistrationDetail> lstUser = new ArrayList<>(); 

      Workbook workbook = null; 

      if (excelfile.getOriginalFilename().endsWith("xlsx")) { 
       workbook = new XSSFWorkbook(excelfile.getInputStream()); 
      } else if (excelfile.getOriginalFilename().endsWith("xls")) { 
       workbook = new HSSFWorkbook(excelfile.getInputStream()); 
      } else { 
       model.addAttribute("msg", new IllegalArgumentException("The specified file is not Excel file")); 
      } 

      Sheet worksheet = workbook.getSheetAt(0); 


     Iterator<Row> iterator = worksheet.iterator(); 
     while (iterator.hasNext()) { 
      Row nextRow = iterator.next(); 
      Iterator<Cell> cellIterator = nextRow.cellIterator(); 
      UserRegistrationDetail user = new UserRegistrationDetail(); 

      while (cellIterator.hasNext()) { 
       Cell nextCell = cellIterator.next(); 
       int columnIndex = nextCell.getColumnIndex(); 

       switch (columnIndex) { 
       case 0: 
        user.setId(String.valueOf(nextCell.getNumericCellValue())); 
        break; 
       case 1: 
        user.setEmail(nextCell.getStringCellValue()); 
        break; 
       case 2: 
        user.setFullname(nextCell.getStringCellValue()); 
        break; 
       } 

      } 
      lstUser.add(user); 
     } 
     model.addAttribute("listUser", lstUser); 
     session.setAttribute("listUserImport", lstUser); 
    } catch (Exception e) { 
     model.addAttribute("msg", e.getMessage()); 
    } 

    return "reportregistrationuser";  
} 

目前我的代碼只讀文件Excel文件像這樣 currently read file

如何實現我的預期結果,我在做什麼?

回答

2

在迭代每一行之前,使用iterator.next()將迭代器最初移動到第二行。 所以在你的循環,它會從第二行開始。

Iterator<Row> iterator = worksheet.iterator(); 
//Add the below line 
Row headerRow= iterator.next();