How to do cell iteration of excel in java

前端 未结 3 1931
情书的邮戳
情书的邮戳 2020-12-10 22:44

I am having an excel with 2 rows and 5 columns. Now I entered code manually to take values from 1st row. How can I iterate the process?

Below is the code for 1st row

相关标签:
3条回答
  • 2020-12-10 23:17

    Use the code below to iterate over all rows of a datasheet:

    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
        }
    }
    
    0 讨论(0)
  • 2020-12-10 23:27
    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 all rows and all cells

    0 讨论(0)
  • 2020-12-10 23:33

    You just need to change 1 to the row number, and use a for loop. Based on your code you could do the following e.g. 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 better 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 讨论(0)
提交回复
热议问题