How to iterate excel cell in java

I have excel with 2 rows and 5 columns. Now I entered the code manually to take values ​​from the 1st line. How can I repeat the process?

Below is the code for 1st line in excel. Starting from the second line, I don't know how to do this ... I want to repeat one line after another.

Workbook workbook = Workbook.getWorkbook(new File(
                               "\\C:\\users\\a-4935\\Desktop\\DataPool_CA.xls"));
Sheet sheet = workbook.getSheet("Sheet1");
System.out.println("Reached to Sheet");
Cell a = sheet.getCell(2,1);
Cell b = sheet.getCell(3,1);
Cell c = sheet.getCell(4,1);
Cell d = sheet.getCell(5,1);
Cell e = sheet.getCell(6,1);
Cell f = sheet.getCell(7,1);
Cell g = sheet.getCell(8,1);
Cell h = sheet.getCell(9,1);
Cell i = sheet.getCell(10,1);

String uId              =   a.getContents();
String deptFromDat      =   b.getContents();
String deptToDate       =   c.getContents();
String dept1            =   d.getContents();
String arrival1         =   e.getContents();
String eihon1           =   f.getContents();
String branchCode1      =   g.getContents();
String userType1        =   h.getContents();
String sessionId1       =   i.getContents();

      

+2


source to share


3 answers


Use the following code to iterate over all rows of the table:

Sheet sheet = workbook.getSheet("Sheet1");
for (Row row : sheet) {
    for (Cell cell : row) {
        //your logic
    }
}

      



Or, alternatively, use the following code:

Sheet sheet = workbook.getSheet("Sheet1");
for (int i = 0; i < 2; i++) {
    Row row = sheet.getRow(i);
    if(row == null) {
        //do something with an empty row
        continue;
    }
    for (int j = 0; j < 5; j++) {
        Cell cell = row.getCell(j);
        if(cell == null) {
            //do something with an empty cell
            continue;
        }
        //your logic
    }
}

      

+9


source


You just need to change 1 to the line number and use a for loop. Based on your code, you can do the following for example. For exmaple:

for(int i=0; i<number; i++)
{

            Cell a = sheet.getCell(2,i);
            Cell b = sheet.getCell(3,i);
            Cell c = sheet.getCell(4,i);
...

}

      



Or better yet, move the Cell declarations out of the for loop, which is best practice.

Cell a,b, c...; 

for(int i=0; i<number; i++)
{

             a = sheet.getCell(2,i);
             b = sheet.getCell(3,i);
             c = sheet.getCell(4,i);
...

}

      

0


source


for (int i = 0; i <= sheet.getLastRowNum (); ++i) {
        row=(Row) sheet.getRow(i);
        Iterator<Cell> cells = row.cellIterator();
        while (cells.hasNext())
        { .....

      

you can use the above code to iterate over all lines and all cells

0


source







All Articles