chinna_82
chinna_82

Reputation: 6403

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.

Upvotes: 0

Views: 6590

Answers (2)

Raghu
Raghu

Reputation: 1393

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;
  ......
}

Upvotes: 1

shreyansh jogi
shreyansh jogi

Reputation: 2102

you can use iterator that allows you to read each and every cell

see example here

Iterator<Row> rowIterator = sheet.iterator();
    while(rowIterator.hasNext()) {
        Row row = rowIterator.next();

        //For each row, iterate through each columns
        Iterator<Cell> cellIterator = row.cellIterator();
        while(cellIterator.hasNext()) {

            Cell cell = cellIterator.next();

            switch(cell.getCellType()) {
                case Cell.CELL_TYPE_BOOLEAN:
                    System.out.print(cell.getBooleanCellValue() + "\t\t");
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    System.out.print(cell.getNumericCellValue() + "\t\t");
                    break;
                case Cell.CELL_TYPE_STRING:
                    System.out.print(cell.getStringCellValue() + "\t\t");
                    break;
            }
        }

Upvotes: 1

Related Questions