Java Poi 读取excel 对所有类型进行处理

1、最近做了一个批量导入功能 , 发现poi读取excel的日期类型会出现问题,源于日期类型分为以下几种:

①、yyyy/MM/dd

②、HH:mm:ss

③、yyyy/MM/dd HH:mm:ss

2、解决思路:

日期,数字的类型都是数值的, 所有需要对每一个进行区分,根据cell.getCellStyle().getDataFormat() 方法  可以得到excel 格子中的short类型的值 ,从断点中得知

    yyyy/MM/dd 格式的值是 14

    HH:mm:ss  格式的值是 21

    yyyy/MM/dd HH:mm:ss 格式的值是 22

   double 和 Int 都是 0 (我都转成转成String 再去做进一步处理)

3、java代码如下:

 1 public static String getCellValue(Cell cell) {
 2         String cellValue = "";
 3         if (cell == null) {
 4             return cellValue;
 5         }
 6         // 判断数据的类型
 7         switch (cell.getCellType()) {
 8         case Cell.CELL_TYPE_NUMERIC: // 数字
 9             //short s = cell.getCellStyle().getDataFormat();
10             if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
11                 SimpleDateFormat sdf = null;
12                 // 验证short值
13                 if (cell.getCellStyle().getDataFormat() == 14) {
14                     sdf = new SimpleDateFormat("yyyy/MM/dd");
15                 } else if (cell.getCellStyle().getDataFormat() == 21) {
16                     sdf = new SimpleDateFormat("HH:mm:ss");
17                 } else if (cell.getCellStyle().getDataFormat() == 22) {
18                     sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
19                 } else {
20                     throw new RuntimeException("日期格式错误!!!");
21                 }
22                 Date date = cell.getDateCellValue();
23                 cellValue = sdf.format(date);
24             } else if (cell.getCellStyle().getDataFormat() == 0) {//处理数值格式
25                 cell.setCellType(Cell.CELL_TYPE_STRING);
26                 cellValue = String.valueOf(cell.getRichStringCellValue().getString());
27             }
28             break;
29         case Cell.CELL_TYPE_STRING: // 字符串
30             cellValue = String.valueOf(cell.getStringCellValue());
31             break;
32         case Cell.CELL_TYPE_BOOLEAN: // Boolean
33             cellValue = String.valueOf(cell.getBooleanCellValue());
34             break;
35         case Cell.CELL_TYPE_FORMULA: // 公式
36             cellValue = String.valueOf(cell.getCellFormula());
37             break;
38         case Cell.CELL_TYPE_BLANK: // 空值
39             cellValue = null;
40             break;
41         case Cell.CELL_TYPE_ERROR: // 故障
42             cellValue = "非法字符";
43             break;
44         default:
45             cellValue = "未知类型";
46             break;
47         }
48         return cellValue;
49     }

注:本文部分内容转载 Java Poi 读取excel 对所有类型进行处理

暂时先标记,日后有完善会更新

 

猜你喜欢

转载自www.cnblogs.com/22MM/p/10278484.html