Read Excel file and skip empty rows but not empty columns

watermelon picture watermelon · Jul 23, 2015 · Viewed 10k times · Source

I wish to read an Excel file and skip the empty rows. My code skips empty cells but it skips empty columns, too. How can I skip empty rows but maintain empty columns? I'm using JXL Java.

for (int i = 0; i < sheet.getRows(); i++) {
    for (int j = 0; j < sheet.getColumns(); j++) {
        Cell cell = sheet.getCell(j, i);
        String con = cell.getContents();
        if (con != null && con.length() != 0) {          
            System.out.print(con);
            System.out.print("|");
        }
        else {
            continue;
        }
    }
}

Answer

user1779715 picture user1779715 · Jul 23, 2015

Try this:

for (int i = 0; i < sheet.getRows(); i++) {
    boolean rowEmpty = true;
    String currentRow = "";
    for (int j = 0; j < sheet.getColumns(); j++) {
        Cell cell = sheet.getCell(j, i);
        String con=cell.getContents();
        if(con !=null && con.length()!=0){
            rowEmpty = false;
        }
        currentRow += con + "|";
    }
    if(!rowEmpty) {
        System.out.println(currentRow);
    }
}

What you were doing is:

  • Loop through rows
    • Loop through columns
      • Print cell if it's empty only, skip it otherwise (your continue statement does nothing as it's the last instruction in the loop anyway, and a break statement would just stop reading the row once it reaches an empty cell)

What this does is:

  • Loop through rows
    • Loop through columns
      • Append the cell to the row's string, and if it's non-empty then set rowEmpty to false (as it contains at least one non-empty cell)
    • Print the row only if it's not empty