Search code examples
javaexcelapache-poixssf

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


I need to parse over an excel sheet and retrieve values from each row to store it in database. Currently I am doing it based on the type of values that each cell holds. This is ok in the current case as I have to deal with only 2 columns. But I have a new requirement to parse an excel sheet that holds more than 12 columns. How can it be done in this case? Is there a way I could iterate each row based on column if I am using a structured table with table headers?

My current code is as follows.

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

            }

I am using the following external apache API imports:

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

Is there a way I can do the same passing in the name of column headers?

Please help.

Thanks in advance.


Solution

  • based on the comments

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