java excel 导入时判断和获取数据

1、判断是不是空行

/**
* 判断是否空行
*/
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;
}

2、判断是不是空单元格

if (null != row.getCell(0) && row.getCell(0).getCellType() != CellType.BLANK && !StringUtils.isBlank(ExcelUtil.getCellValue(row.getCell(0)))) {}

3、读取单元格返回的都是字符串的方法

/***
* 读取单元格的值
*
* @Title: getCellValue
* @Date : 2014-9-11 上午10:52:07
* @param cell
* @return
*/
public static String getCellValue(Cell cell) {
Object result = "";
if (cell != null) {
switch (cell.getCellType()) {
case STRING:
result = cell.getStringCellValue();
break;
case NUMERIC:
result = cell.getNumericCellValue();
break;
case BOOLEAN:
result = cell.getBooleanCellValue();
break;
case FORMULA:
result = cell.getCellFormula();
break;
case ERROR:
result = cell.getErrorCellValue();
break;
case BLANK:
break;
default:
break;
}
}
return result.toString();
}

3、判断字符串是不是空的

if (null != row.getCell(0) && row.getCell(0).getCellType() != CellType.BLANK && !StringUtils.isBlank(ExcelUtil.getCellValue(row.getCell(0)))) {
String cellValue = ExcelUtil.getCellValue(row.getCell(0));
String splitHeadAndEndCellValue = cellValue.trim();
} else {
}

4、判断是不是数字类型

if (null != row.getCell(1) && row.getCell(1).getCellType() != CellType.BLANK) {
String cellValue = ExcelUtil.getCellValue(row.getCell(1));
try {
Double i1 = Double.parseDouble(cellValue);
if (i1 <= 0) {
message.append("第" + (i + 1) + "行第2列xxxx 不是大于0的数字" + cellValue + " ; ");
}
BigDecimal b = new BigDecimal(i1);
//保留两位小时
i1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
product.setOverseasMasterBoxGrossWeightKgs(i1);
} catch (Exception exception) {
exception.getStackTrace();
exception.getMessage();
message.append("第" + (i + 1) + "行第2列xxx 不是数字" + cellValue + " ; ");
}
} else {

}

5、判断是不是整数

if (null != row.getCell(2) && row.getCell(2).getCellType() != CellType.BLANK) {
//将单元格设置成字符串类型,如果是整数,读取到的会是Double类型,所以需要设置成CellType.STRING
row.getCell(2).setCellType(CellType.STRING);
String cellValue = ExcelUtil.getCellValue(row.getCell(2));
try {
int i1 = Integer.parseInt(cellValue);
if (i1 <= 0) {
message.append("第" + (i + 1) + "行第3列xxx 不是大于0的整数" + cellValue + " ; ");
}
product.setOverseasMasterCtn(i1);
} catch (Exception exception) {
exception.getStackTrace();
exception.getMessage();
message.append("第" + (i + 1) + "行第3列xxxx 不是大于0的整数" + cellValue + " ; ");
}
} else {
}
CellType类型以及值的对应关系
CellType 类型
CELL_TYPE_NUMERIC 数值 0
CELL_TYPE_STRING 字符串型 1
CELL_TYPE_FORMULA 公式型 2
CELL_TYPE_BLANK 空值 3
CELL_TYPE_BOOLEAN 布尔型 4
CELL_TYPE_ERROR 错误 5