POI删除空白行 代码和其他用法(将会持续更新)

目的

要根据后端值是否有无来判断是否删除空白行
以下数据都经过处理,不涉及公司机密
在这里插入图片描述

有三种投放方式,如果后端有值,则显示,没有值,则文档删除此行

代码

public class Utils {
    
    
    // 获取准确的文件行数
    public Sheet getAccuracyContextNum(Sheet sheet) {
    
    
        // 删除空行
        for (int i = 0; i <= sheet.getLastRowNum(); i++) {
    
    
            Row row = sheet.getRow(i);
            // 删除空行
            if (this.isRowEmpty(row)) {
    
    
                int lastRowNum = sheet.getLastRowNum();
                if (i >= 0 && i < lastRowNum) {
    
    
                    sheet.shiftRows(i + 1, lastRowNum, -1);// 将行号为i+1一直到行号为lastRowNum的单元格全部上移一行,以便删除i行
                }
                if (i == lastRowNum) {
    
    
                    if (row != null) {
    
    
                        sheet.removeRow(row);
                    }
                }
                i--;
            }
        }
        return sheet;
    }

    // 判断行是否为空
    public static boolean isRowEmpty(Row row) {
    
    
        for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
    
    
            Cell cell = row.getCell(c);
            if (cell != null && cell.getCellType() != CellType.BLANK) {
    
      //此处判断得根据poi版本来修改相应判断
                return false;
            }
        }
        return true;
    }

}

结果

因为写博客和写代码的电脑不是同一台,就用自己电脑写一个小demo返回控制台输出

不加删除空白行代码情况

代码
不加代码返回情况

加上删除空白行代码情况

加上代码返回结果

POI 其他用法

设置行高

POI中行高和Excel中行高单位是不一样的
POI中的行高单位是twips;
Excel中的行高单位是pt;

1pt=20twips

所以,当我想要Excel行高为30的时候,代码将应该这样设置

row.setHeight((short) 30*20 );

合并单元格

//合并单元格
//四个参数分别是 起始行,结束行,起始列,结束列
//从第21行到21行,从第1列开始到4列合并 (即为图片效果)
CellRangeAddress cellRangeAddress = new CellRangeAddress(20,20,0,3);
sheetAt.addMergedRegion(cellRangeAddress);

删除整行

sheet.removeRow(row);

注意:此代码不能和shiftRows一起用,不然!它会把那一行从整个list里面删掉导致用shiftRows的时候根本就没有那一行然后空指针

猜你喜欢

转载自blog.csdn.net/weixin_46573158/article/details/125970711
今日推荐