Search code examples
javaexcelcell

Java - Excel read multiple row data


I need to read excel file which more than 300 rows. I need to extract value from particular cell only.

Code

Workbook workbook = Workbook.getWorkbook(new File(excelFile));
Sheet sheet = workbook.getSheet(0);
Cell emp_name = sheet.getCell(1,2); 
Cell emp_dpt = sheet.getCell(2,2); 
Cell emp_pdpt = sheet.getCell(3,2); 
Cell emp_no = sheet.getCell(4,2);
Cell emp_desn = sheet.getCell(5,2);
Cell emp_dj = sheet.getCell(6,2);
Cell emp_lvl = sheet.getCell(7,2);
Cell emp_eval = sheet.getCell(8,2);              

String name = emp_name.getContents(); 
String dpartment = emp_dpt.getContents(); 
String pre_department = emp_pdpt.getContents();
String employee_no = emp_no.getContents(); 
String designation = emp_desn.getContents(); 
String datejoined = emp_dj.getContents();
String evalution = emp_eval.getContents();
System.out.println(name);
System.out.println(dpartment);
System.out.println(pre_department);
System.out.println(employee_no);
System.out.println(designation);
System.out.println(datejoined);
System.out.println(evalution);

Above code helps me to fetch data from the excel but only one value extracted. How do I fetch all the data from excel.


Solution

  • Do it in a loop

    When you say , sheet.getCell(1,2), you read the cell with column 1 and row 2.

    Support if you want to read , column 1 and row 3, then do this sheet.getCell(1,3);

    sheet.getRows() ->Returns the number of rows in this sheet

    pseudo code:

    for (int rowNum = 5; rowNum < sheet.getRows(); rowNum++) {
    int column = 4;
      sheet.getCell(column ++, rowNum).getContents(); //read 4th column and 5th row into a variable or object as per your logic;
      sheet.getCell(column ++, rowNum).getContents(); //read 5th column and 5th row;
      ......
    }