简体   繁体   中英

Why am I getting the number of rows in an Excel sheet as 0 using JAVA?

I am trying to write some data into an Excel file with format (.xlsx). But the thing is that the first row of it is written into the file correctly and when I am trying to retrieve the number of rows and then increment the rows so that I could write more rows into the file, I am getting an exception of "Invalid format exception" and sometimes my code is getting executed but I am getting row count as 1. Please solve my issue and I am even attaching the code am working with.

public static int getRows(String memail,String testid) throws FileNotFoundException,IOException, InvalidFormatException{
            int rc;         

            FileInputStream file = new FileInputStream(new File("email1.xlsx"));

                XSSFWorkbook wb = new XSSFWorkbook (file);
                WorkbookFactory.create(file);

                XSSFSheet sheet = wb.getSheet(testid);

                rc = sheet.getLastRowNum();

               return rc;

       }

Remove the following line

   WorkbookFactory.create(file);

and try again.

If you have already a created file, while you are creating that again...

You can try Sheet.getPhysicalNumberOfRows() , this will returns the number of physically defined rows (NOT the number of rows in the sheet).
One more point are you sure you are getting the correct sheet from wb.getSheet(testid); ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM