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.

我希望阅读一个Excel文件并跳过空行。我的代码跳过空单元格,但它也会跳过空列。如何跳过空行但保留空列?我正在使用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;
        }
    }
}

1 个解决方案

#1


1

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)
      • 打印单元格如果它只是空的,否则跳过它(你的continue语句什么也不做,因为它是循环中的最后一条指令,并且一旦它到达一个空单元格,break语句就会停止读取它)

    • 循环遍历列打印单元格如果它只是空的,否则跳过它(你的continue语句不执行任何操作,因为它是循环中的最后一条指令,并且一旦它到达空单元格,break语句就会停止读取该行)

  • 循环遍历行循环遍历列打印单元格如果它只是空的,否则跳过它(你的continue语句不执行任何操作,因为它是循环中的最后一条指令,并且一旦它到达空单元格,break语句就会停止读取该行)

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)
      • 将单元格附加到行的字符串,如果它是非空的,则将rowEmpty设置为false(因为它包含至少一个非空单元格)

    • 循环遍历列将单元格附加到行的字符串,如果它是非空的,则将rowEmpty设置为false(因为它包含至少一个非空单元格)

    • Print the row only if it's not empty
    • 仅当行不为空时才打印该行

  • 遍历行循环遍历列将单元格附加到行的字符串,如果它是非空的,则将rowEmpty设置为false(因为它至少包含一个非空单元格)仅在它不为空时才打印该行

更多相关文章

  1. 字体图标的引入和通过媒体查询改变导航样式
  2. HTML样式和常用选择器
  3. 字体图标的引用和自定义样式/媒体查询的使用
  4. 数据库的CURD操作、PDO本质与原理的学习
  5. CSS之伪类选择器和简单盒子简单案例
  6. 伪类选择器与盒模型常用属性
  7. 伪类选择器-结构伪类、根据位置选择匹配
  8. 7.4——常用标签与应用场景之表格与单元格
  9. css伪类选择器和盒模型

随机推荐

  1. 详解php版阿里云OSS图片上传类
  2. 全栈工程师看过来!PHP Javascript语法对照
  3. php array_combine()函数实例详解
  4. 示例php+mysql查询实现无限下级分类树输
  5. 一起看看PHP执行普通shell命令流程
  6. 实现PHP+Mysql无限分类的方法
  7. 学习php简单实现短网址(短链)还原的方法
  8. 详解php命令行写shell实例
  9. 分享4个提高脚本性能的PHP技巧
  10. 分析php生成短网址/短链接原理和用法实例