poi删除空行

	// 获取准确的文件行数
	public Sheet getAccuracyContextNum(XSSFSheet 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) {
				return false;
			}
		}
		return true;
	}

改进:删除sheet后面的空行

	public Sheet getAccuracyContextNum(XSSFSheet sheet) {
		// 删除空行
		for (int i = sheet.getLastRowNum(); i >= 0; i--) {
			Row row = sheet.getRow(i);
			int c = row.getFirstCellNum();
			Cell cell = row.getCell(c);
			if (cell.getCellType() != CellType.STRING) {
				sheet.removeRow(row);
			} else {
				break;
			}			
		}
		return sheet;
	}
posted @ 2020-11-10 10:46  轩辕吊雷  阅读(1269)  评论(0)    收藏  举报