如何使用列名迭代 excel sheet 中的当前行?

How to iterate over current row in an excel sheet using column name?

我需要解析 excel sheet 并从每一行中检索值以将其存储在数据库中。目前我是根据每个单元格所持有的值的类型来做的。在当前情况下这是可以的,因为我只需要处理 2 列。但是我有一个新的要求来解析一个包含超过 12 列的 excel sheet。在这种情况下怎么办?如果我使用结构化 table 和 table headers?

,有没有一种方法可以根据列迭代每一行

我目前的代码如下。

        File file = new File(UPLOAD_LOCATION + fileUpload.getFile().getOriginalFilename());
        FileInputStream excelFile = new FileInputStream(file);

        Workbook workbook = new XSSFWorkbook(excelFile);
        Sheet datatypeSheet = workbook.getSheetAt(0);
        Iterator<Row> iterator = datatypeSheet.iterator();
        while (iterator.hasNext()) {
            Row currentRow = iterator.next();
            Iterator<Cell> cellIterator = currentRow.iterator();

            while (cellIterator.hasNext()) {

                Cell currentCell = cellIterator.next();
                // getCellTypeEnum shown as deprecated for version 3.15
                // getCellTypeEnum ill be renamed to getCellType starting
                // from version 4.0
                if (currentCell.getCellTypeEnum() == CellType.STRING) {
                    System.out.print(currentCell.getStringCellValue() + "--");
                } else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) {
                    System.out.print(currentCell.getNumericCellValue() + "--");
                }

            }

我正在使用以下外部 apache API 导入:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

有没有一种方法可以通过传递列名 headers 来做同样的事情?

请帮忙。

提前致谢。

基于评论

    InputStream excelFile = new FileInputStream(file);
    Workbook workbook = new XSSFWorkbook(excelFile);
    ArrayList colsList=new ArrayList();
    colsList.add("Col1");
    colsList.add("Col2");
    colsList.add("Col3");
    colsList.add("Col4");
    Sheet datatypeSheet = workbook.getSheetAt(0);
    int numOfRows=datatypeSheet.getLastRowNum();
    for(int rowNum=0;rowNum<numOfRows;rowNum++){
    Row row=datatypeSheet.getRow(rowNum);
    int numOfCellPerRow=row.getLastCellNum();
    for(int cellNum=0;cellNum<numOfCellPerRow;cellNum++){
    if(colsList.contains(row.getCell(rowNum).getStringCellValue())){
    Cell cell=row.getCell(cellNum)
    System.out.println("Cell No:"+cellNum+" value is: 
    "+cell.getStringCellValue())
    }
   }
     System.out.println("This is a new Row");
   }