Java利用Poi讀取excel并對所有類型進行處理
1.最近做了一個批量導入功能 , 然后發(fā)現(xiàn)poi讀取excel的日期類型會出現(xiàn)點問題 , 因為我的需求是需要區(qū)分出
yyyy/MM/dd ,HH:mm:ss ,yyyy/MM/dd HH:mm:ss
2.日期,數字的類型都是數值的, 所有需要對每一個進行區(qū)分
根據cell.getCellStyle().getDataFormat() 方法 可以得到excel 格子中的short類型的值 ,從斷點中得知
yyyy/MM/dd 格式的值是 14
HH:mm:ss 格式的值是 21
yyyy/MM/dd HH:mm:ss 格式的值是 22
double 和 Int 都是 0 (我都轉成轉成String 再去做進一步處理)
下面是代碼可以把值寫成常量定義
public static String getCellValue(Cell cell) { String cellValue = ""; if (cell == null) { return cellValue; } // 判斷數據的類型 switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: // 數字 //short s = cell.getCellStyle().getDataFormat(); if (HSSFDateUtil.isCellDateFormatted(cell)) {// 處理日期格式、時間格式 SimpleDateFormat sdf = null; // 驗證short值 if (cell.getCellStyle().getDataFormat() == 14) { sdf = new SimpleDateFormat("yyyy/MM/dd"); } else if (cell.getCellStyle().getDataFormat() == 21) { sdf = new SimpleDateFormat("HH:mm:ss"); } else if (cell.getCellStyle().getDataFormat() == 22) { sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); } else { throw new RuntimeException("日期格式錯誤!!!"); } Date date = cell.getDateCellValue(); cellValue = sdf.format(date); } else if (cell.getCellStyle().getDataFormat() == 0) {//處理數值格式 cell.setCellType(Cell.CELL_TYPE_STRING); cellValue = String.valueOf(cell.getRichStringCellValue().getString()); } break; case Cell.CELL_TYPE_STRING: // 字符串 cellValue = String.valueOf(cell.getStringCellValue()); break; case Cell.CELL_TYPE_BOOLEAN: // Boolean cellValue = String.valueOf(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_FORMULA: // 公式 cellValue = String.valueOf(cell.getCellFormula()); break; case Cell.CELL_TYPE_BLANK: // 空值 cellValue = null; break; case Cell.CELL_TYPE_ERROR: // 故障 cellValue = "非法字符"; break; default: cellValue = "未知類型"; break; } return cellValue; }
到此這篇關于Java利用Poi讀取excel并對所有類型進行處理的文章就介紹到這了,更多相關Java Poi讀取excel內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!