java 读取excel获取真实行数

刚进入公司开发,熟悉环境是个很大的难题,今天就接到了一个任务,让我修改批量上传excel文件的页面. 
公司采用的是apache提供的包,通过XML文件的映射,把EXCEL表和我们的Model对应起来.本来是校验正确的,结果莫名其妙到后面就会报空指针异常. 
问题的原因:在没有格式的前提下,getLastRowNum方法能够正确返回最后一行的位置;getPhysicalNumberOfRows方法能够正确返回物理的行数; 
* 在有格式的前提下,这两个方法都是不合理的; 
* 所以,在做导入excel的时候,建议想要正确获取行数,可以做一个人为的约定,比如约定导入文件第一列不允许为空,行数就按照第一列的有效行数来统计;这样就能正确获取到实际想要的行数;

更新版本, 因为发现有时候 存在了加了样式的边框,边框的属性默认成为了 公式属性,导致后面空指针,现已修复

修改版
 

/**
 * 用来得到真实行数
 * @param sheet
 * @param flag  需要写进数据库的列数用逗号隔开 比如  (Sheet sheet,int 2,int 3);随意个
 * @return
 * 
 */
public static int findRealRows(Sheet sheet, int... flag) {
	int row_real = 0;
	int rows = sheet.getPhysicalNumberOfRows();// 此处物理行数统计有错误,
	int size = flag.length;
	try {


	for (int i = 1; i < rows; i++) {
		Row row = sheet.getRow(i);
		int total = 0;
		ArrayList<Integer> blank =new ArrayList<Integer>();
		int type=-1;
		String s = null;
		for(int j:flag){
			if(!(row.getCell(j) == null)&&row.getCell(j).getCellType()<2){
				type=row.getCell(j).getCellType();
				row.getCell(j).setCellType(1);
			}

			if (row.getCell(j) == null||row.getCell(j).getStringCellValue().matches("^\\s+$")||row.getCell(j).getCellType()>2) {
				total++;

				if(!(row.getCell(j) == null)&&row.getCell(j).getCellType()<2){
				row.getCell(j).setCellType(type);
				}
				blank.add(j);

			}
		}
		System.out.println(s+"我");
		// 如果4列都是空说明就该返回
		if (total == flag.length) {

			return row_real;
		} else if (total == 0) {
			row_real++;

		} else {
			String h="";
			for(Integer b:blank){

				 h=h+"第"+(b+1)+"列"+" ";
			}
			throw new BusinessException("第" + (i + 1) + "行" + h
					+ "不能为空");
		}

	}
	} catch (NullPointerException e) {
		throw new BusinessException("excel格式异常,请检查excel格式有无数据缺失,无效数据行!");
	}
	return row_real;
}

方法都这样,通过约定一个有的ID来进行判断,可以较快的得到真实的行数 ,以至于后面的集合循环输出的话不会出现空指针异常

原文地址:https://blog.csdn.net/hn5091/article/details/44179961

猜你喜欢

转载自blog.csdn.net/qq_19734597/article/details/83856320