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");


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM