Read Excel file and skip blank lines but not blank columns

I want to read an Excel file and skip blank lines. My code is skipping empty cells but also skipping empty columns. How can I skip empty rows, but keep empty columns? I am 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;
        }
    }
}

      

+3


source to share


1 answer


Try the following:

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 did you do:



  • Scrolling lines
    • Loop through columns
      • Print the cell if it is empty, skip otherwise (your continue statement does nothing as it is the last statement in the loop, and the break statement will just stop reading the line when it reaches an empty cell)

What it is:

  • Scrolling lines
    • Loop through columns
      • Append the cell to the row of the row, and if it is not empty, set the rowEmpty parameter to false (since it contains at least one non-empty cell)
    • Print the line only if it is not empty.
+1


source







All Articles