读取不带标题的 POI 的 Excel 文件

unk*_*own 2 java excel apache-poi

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

这是我的代码

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";    
}
Run Code Online (Sandbox Code Playgroud)

目前我的代码只能像这样读取文件 excel 当前读取文件

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

vik*_*iii 6

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

Iterator<Row> iterator = worksheet.iterator();
//Add the below line 
 Row headerRow= iterator.next();
Run Code Online (Sandbox Code Playgroud)