java导入excel很完美的取值的方法 java导入excel很完美的取值的方法

 

1.解决方法:

/**
   * 获取单元格数据内容为字符串类型的数据
   * @param cell Excel单元格
   * @return String 单元格数据内容
   */
  private  String getStringCellValue(Cell cell,String format) {
      String strCell = "";
      switch (cell.getCellType()) {
          case XSSFCell.CELL_TYPE_STRING:
              Pattern p = Pattern.compile("^[0-9]{4}[\.\-/](0?[1-9]|1[0-2])[\.\-/](0?[1-9]|[1-2][0-9]|3[0-1])$");  
              Matcher m = p.matcher(cell.getStringCellValue());  
              boolean b = m.matches();  
              if(b)  
              {  
                  strCell=cell.getStringCellValue().replaceAll("[\./]""-");
              }  
              else
              {  
                  strCell = cell.getStringCellValue();
              }  
              break;
          case XSSFCell.CELL_TYPE_NUMERIC:
              if (DateUtil.isCellDateFormatted(cell)) {
                  //  如果是date类型则 ,获取该cell的date值
                  strCell = newSimpleDateFormat(format).format(DateUtil.getJavaDate(cell.getNumericCellValue()));
              else // 纯数字
                  cell.setCellType(Cell.CELL_TYPE_STRING);
                  strCell = String.valueOf(cell.getStringCellValue());
              }
                  break;
          case XSSFCell.CELL_TYPE_BOOLEAN:
              strCell = String.valueOf(cell.getBooleanCellValue());
              break;
          case XSSFCell.CELL_TYPE_BLANK:
              strCell = "";
              break;
          default:
              strCell = "";
              break;
      }
      if (strCell.equals("") || strCell == null) {
          return "";
      }
      if (cell == null) {
          return "";
      }
      return strCell;

  }

2.用法:

getStringCellValue(cell,"yyyy-MM-dd");

getStringCellValue(cell,"yyyy-MM-dd HH:mm:ss");

getStringCellValue(cell,"HH:mm:ss");