使用POI读取Excel文件而不使用标题

时间:2016-06-10 02:50:46

标签: java excel apache-poi

我想使用没有标题标题的poi读取excel文件,我的预期结果 expected read excel file

这是我的代码

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

如何实现我的预期结果,我在做什么?

1 个答案:

答案 0 :(得分:2)

在迭代每一行之前,先使用iterator.next()将迭代器移动到第二行。 因此,在 while 循环中,它将从第2行开始。

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