适用poi版本:5.2.2
1.行索引获取Row对象
可能sheet页对象没有创建这一行,可能为空,为空时先创建Row再返回
public static Row safeRow(Sheet sheet,int i){
Row row = sheet.getRow(i);
if(row == null){
row = sheet.createRow(i);
}
return row;
}
2.列索引获取Cell对象
封装该方法的原因和上面一样,getCell可能为空
public static Cell safeCell(Row row,int i){
Cell cell = row.getCell(i);
if(cell == null){
cell = row.createCell(i);
}
return cell;
}
3.读取单元格数据
excel中支持多种数据格式,分别对应java中的Double、String、Date、Boolean,根据单元格的getCellType()方法判断单元格类型,返回对应类型的数据
private static final List<Integer> EXCEL_DATE_FORMAT_LIST = Arrays.asList(14,31,57,58);
/**
* 获得单元格数据
*/
public static Object getCellValue(Cell cell, FormulaEvaluator evaluator){
if (cell == null){ return null;}
if(Objects.equals(cell.getCellType(),CellType.STRING)){
return cell.getStringCellValue();
}else if(Objects.equals(cell.getCellType(),CellType.NUMERIC)){
if(DateUtil.isCellDateFormatted(cell)){
return cell.getDateCellValue();
}else if (EXCEL_DATE_FORMAT_LIST.contains((int) cell.getCellStyle().getDataFormat())) {
// 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是14,31,57,58)
double cellValue = cell.getNumericCellValue();
return DateUtil.getJavaDate(cellValue);
}else {
return NumberToTextConverter.toText(cell.getNumericCellValue());
}
}else if(Objects.equals(cell.getCellType(),CellType.BLANK)){
return "";
}else if(Objects.equals(cell.getCellType(),CellType.FORMULA)){
CellValue value = evaluator.evaluate(cell);
if(value.getCellType() == CellType.NUMERIC){
return NumberToTextConverter.toText(value.getNumberValue());
}else if(value.getCellType() == CellType.BOOLEAN){
return String.valueOf(value.getBooleanValue());
}else{
return value.getStringValue();
}

最低0.47元/天 解锁文章
3万+

被折叠的 条评论
为什么被折叠?



