1. 程式人生 > >java匯入excel很完美的取值的方法

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 =  new SimpleDateFormat(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");