java通过poi读取excel中的日期类型数据或自定义类型日期
java通過poi讀取excel中的日期類型數(shù)據(jù)或自定義類型日期
Java 讀取Excel表格日期類型數(shù)據(jù)的時(shí)候,讀出來的是這樣的 ?12-十月-2019,而Excel中輸入的是 2019/10/12 或 2019-10-12
poi處理excel時(shí),當(dāng)excel沒有明確指明是哪個(gè)類型的數(shù)據(jù)時(shí),poi很可能處理單元格的日期數(shù)據(jù)時(shí)就有可能是一串?dāng)?shù)字,而使用java程序基本無法轉(zhuǎn)換。
為了解決以上的問題,本人收集了各種資料,目前來總結(jié)一下,供碰到此類問題的你作參考。
Excel數(shù)據(jù)處理:
Excel存儲(chǔ)日期、時(shí)間均以數(shù)值類型進(jìn)行存儲(chǔ),讀取時(shí)POI先判斷是是否是數(shù)值類型,再進(jìn)行判斷轉(zhuǎn)化
1、數(shù)值格式(CELL_TYPE_NUMERIC):
1.純數(shù)值格式:getNumericCellValue() 直接獲取數(shù)據(jù)
2.日期格式:處理yyyy-MM-dd, d/m/yyyy h:mm,?HH:mm?等不含文字的日期格式
1).判斷是否是日期格式:HSSFDateUtil.isCellDateFormatted(cell)
所有日期格式都可以通過getDataFormat()值來判斷
yyyy-MM-dd----- 14 yyyy年m月d日--- 31 yyyy年m月------- 57 m月d日 ---------- 58 HH:mm----------- 20 h時(shí)mm分 ------- 32接下來是針對(duì)excel各種數(shù)據(jù)類型來進(jìn)入轉(zhuǎn)換,基本涵蓋所需要的,如果沒有你需要的,可以在此基礎(chǔ)上添加
//獲取單元格各類型值,返回字符串類型public static String getCellValueByCell(Cell cell) {//判斷是否為null或空串if (cell==null || cell.toString().trim().equals("")) {return "";}String cellValue = "";int cellType=cell.getCellType();switch (cellType) {case Cell.CELL_TYPE_NUMERIC: // 數(shù)字short format = cell.getCellStyle().getDataFormat();if (DateUtil.isCellDateFormatted(cell)) {SimpleDateFormat sdf = null; //System.out.println("cell.getCellStyle().getDataFormat()="+cell.getCellStyle().getDataFormat());if (format == 20 || format == 32) { sdf = new SimpleDateFormat("HH:mm"); } else if (format == 14 || format == 31 || format == 57 || format == 58) { // 處理自定義日期格式:m月d日(通過判斷單元格的格式id解決,id的值是58) sdf = new SimpleDateFormat("yyyy-MM-dd"); double value = cell.getNumericCellValue(); Date date = org.apache.poi.ss.usermodel.DateUtil .getJavaDate(value); cellValue = sdf.format(date); }else {// 日期 sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } try {cellValue = sdf.format(cell.getDateCellValue());// 日期} catch (Exception e) {try {throw new Exception("exception on get date data !".concat(e.toString()));} catch (Exception e1) {e1.printStackTrace();}}finally{sdf = null;}} else {BigDecimal bd = new BigDecimal(cell.getNumericCellValue()); cellValue = bd.toPlainString();// 數(shù)值 這種用BigDecimal包裝再獲取plainString,可以防止獲取到科學(xué)計(jì)數(shù)值}break;case Cell.CELL_TYPE_STRING: // 字符串cellValue = cell.getStringCellValue();break;case Cell.CELL_TYPE_BOOLEAN: // BooleancellValue = cell.getBooleanCellValue()+"";;break;case Cell.CELL_TYPE_FORMULA: // 公式cellValue = cell.getCellFormula();break;case Cell.CELL_TYPE_BLANK: // 空值cellValue = "";break;case Cell.CELL_TYPE_ERROR: // 故障cellValue = "ERROR VALUE";break;default:cellValue = "UNKNOW VALUE";break;}return cellValue;}?
每天學(xué)習(xí)一點(diǎn)點(diǎn),你就進(jìn)步一點(diǎn)點(diǎn)。
總結(jié)
以上是生活随笔為你收集整理的java通过poi读取excel中的日期类型数据或自定义类型日期的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IP暴露接口IP白名单设置
- 下一篇: springboot yml里面配置