How to get row count in an Excel file using POI library?

前端 未结 7 2194
执念已碎
执念已碎 2020-12-08 09:37

Guys I\'m currently using the POI 3.9 library to work with excel files. I know of the getLastRowNum() function, which returns a number of rows in an Excel file.

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 09:51

    If you do a check

    if
    (getLastRowNum()<1){
     res="Sheet Cannot be empty";
    return
    }
    

    This will make sure you have at least one row with data except header. Below is my program which works fine. Excel file has three columns ie. ID, NAME , LASTNAME

    XSSFWorkbook workbook = new XSSFWorkbook(inputstream);
            XSSFSheet sheet = workbook.getSheetAt(0);
            Row header = sheet.getRow(0);
            int n = header.getLastCellNum();
            String header1 = header.getCell(0).getStringCellValue();
            String header2 = header.getCell(1).getStringCellValue();
            String header3 = header.getCell(2).getStringCellValue();
            if (header1.equals("ID") && header2.equals("NAME")
                    && header3.equals("LASTNAME")) {
                if(sheet.getLastRowNum()<1){
                    System.out.println("Sheet empty");
                             return;
                }   
                            iterate over sheet to get cell values
            }else{
                              SOP("invalid format");
                              return;
                              }
    

提交回复
热议问题