List of usage examples for org.apache.poi.hssf.usermodel HSSFCell getStringCellValue
public String getStringCellValue()
From source file:com.glaf.core.todo.util.TodoXlsReader.java
License:Apache License
public List<Todo> readXls(java.io.InputStream inputStream) { List<Todo> todos = new java.util.ArrayList<Todo>(); HSSFWorkbook wb = null;//from w ww . ja v a2 s . com try { wb = new HSSFWorkbook(inputStream); HSSFSheet sheet = wb.getSheetAt(0); HSSFRow row = sheet.getRow(1); Map<Integer, String> keyMap = new java.util.HashMap<Integer, String>(); Map<String, Object> dataMap = new java.util.HashMap<String, Object>(); int cells = row.getPhysicalNumberOfCells(); for (int colIndex = 0; colIndex < cells; colIndex++) { HSSFCell cell = row.getCell(colIndex); keyMap.put(colIndex, cell.getStringCellValue()); } int sortNo = 1; Set<String> keys = new HashSet<String>(); for (int rowIndex = 2; rowIndex < sheet.getPhysicalNumberOfRows(); rowIndex++) { HSSFRow rowx = sheet.getRow(rowIndex); if (rowx == null) { continue; } // System.out.println(); dataMap.clear(); for (int colIndex = 0; colIndex < cells; colIndex++) { String fieldName = keyMap.get(colIndex); HSSFCell cell = rowx.getCell(colIndex); if (cell == null) { continue; } Object cellValue = null; switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_FORMULA: break; case HSSFCell.CELL_TYPE_BOOLEAN: cellValue = cell.getBooleanCellValue(); break; case HSSFCell.CELL_TYPE_NUMERIC: cellValue = cell.getNumericCellValue(); break; case HSSFCell.CELL_TYPE_STRING: if (StringUtils.isNotEmpty(cell.getRichStringCellValue().getString())) { cellValue = cell.getRichStringCellValue().getString(); } break; default: if (StringUtils.isNotEmpty(cell.getStringCellValue())) { cellValue = cell.getStringCellValue(); } break; } if (cellValue != null) { dataMap.put(fieldName, cellValue); // System.out.print("\t" + fieldName + "=" + cellValue); } } if (dataMap.get("code") != null) { String id = ParamUtils.getString(dataMap, "id"); Todo model = new Todo(); dataMap.remove("id"); Tools.populate(model, dataMap); if (!keys.contains(model.getCode())) { model.setSortNo(sortNo++); if (id != null) { model.setId(Long.parseLong(id)); } if (ParamUtils.getDouble(dataMap, "limitDay") > 0) { model.setLimitDay(ParamUtils.getInt(dataMap, "limitDay")); } todos.add(model); keys.add(model.getCode()); } } } } catch (Exception ex) { throw new RuntimeException(ex); } finally { if (wb != null) { try { wb.close(); wb = null; } catch (IOException e) { } } } return todos; }
From source file:com.haulmont.yarg.formatters.impl.xls.hints.CustomCellStyleHint.java
License:Apache License
@Override public void apply() { for (DataObject dataObject : data) { HSSFCell templateCell = dataObject.templateCell; HSSFCell resultCell = dataObject.resultCell; BandData bandData = dataObject.bandData; HSSFWorkbook resultWorkbook = resultCell.getSheet().getWorkbook(); HSSFWorkbook templateWorkbook = templateCell.getSheet().getWorkbook(); String templateCellValue = templateCell.getStringCellValue(); Matcher matcher = pattern.matcher(templateCellValue); if (matcher.find()) { String paramName = matcher.group(1); String styleName = (String) bandData.getParameterValue(paramName); if (styleName == null) continue; HSSFCellStyle cellStyle = styleCache.getStyleByName(styleName); if (cellStyle == null) continue; HSSFCellStyle resultStyle = styleCache.getNamedCachedStyle(cellStyle); if (resultStyle == null) { HSSFCellStyle newStyle = resultWorkbook.createCellStyle(); // color newStyle.setFillBackgroundColor(cellStyle.getFillBackgroundColor()); newStyle.setFillForegroundColor(cellStyle.getFillForegroundColor()); newStyle.setFillPattern(cellStyle.getFillPattern()); // borders newStyle.setBorderLeft(cellStyle.getBorderLeft()); newStyle.setBorderRight(cellStyle.getBorderRight()); newStyle.setBorderTop(cellStyle.getBorderTop()); newStyle.setBorderBottom(cellStyle.getBorderBottom()); // border colors newStyle.setLeftBorderColor(cellStyle.getLeftBorderColor()); newStyle.setRightBorderColor(cellStyle.getRightBorderColor()); newStyle.setBottomBorderColor(cellStyle.getBottomBorderColor()); newStyle.setTopBorderColor(cellStyle.getTopBorderColor()); // alignment newStyle.setAlignment(cellStyle.getAlignment()); newStyle.setVerticalAlignment(cellStyle.getVerticalAlignment()); // misc DataFormat dataFormat = resultWorkbook.getCreationHelper().createDataFormat(); newStyle.setDataFormat(dataFormat.getFormat(cellStyle.getDataFormatString())); newStyle.setHidden(cellStyle.getHidden()); newStyle.setLocked(cellStyle.getLocked()); newStyle.setIndention(cellStyle.getIndention()); newStyle.setRotation(cellStyle.getRotation()); newStyle.setWrapText(cellStyle.getWrapText()); // font HSSFFont cellFont = cellStyle.getFont(templateWorkbook); HSSFFont newFont = fontCache.getFontByTemplate(cellFont); if (newFont == null) { newFont = resultWorkbook.createFont(); newFont.setFontName(cellFont.getFontName()); newFont.setItalic(cellFont.getItalic()); newFont.setStrikeout(cellFont.getStrikeout()); newFont.setTypeOffset(cellFont.getTypeOffset()); newFont.setBoldweight(cellFont.getBoldweight()); newFont.setCharSet(cellFont.getCharSet()); newFont.setColor(cellFont.getColor()); newFont.setUnderline(cellFont.getUnderline()); newFont.setFontHeight(cellFont.getFontHeight()); newFont.setFontHeightInPoints(cellFont.getFontHeightInPoints()); fontCache.addCachedFont(cellFont, newFont); }//from w ww .j a v a2s .c o m newStyle.setFont(newFont); resultStyle = newStyle; styleCache.addCachedNamedStyle(cellStyle, resultStyle); } fixNeighbourCellBorders(cellStyle, resultCell); resultCell.setCellStyle(resultStyle); Sheet sheet = resultCell.getSheet(); for (int i = 0; i < sheet.getNumMergedRegions(); i++) { CellRangeAddress mergedRegion = sheet.getMergedRegion(i); if (mergedRegion.isInRange(resultCell.getRowIndex(), resultCell.getColumnIndex())) { int firstRow = mergedRegion.getFirstRow(); int lastRow = mergedRegion.getLastRow(); int firstCol = mergedRegion.getFirstColumn(); int lastCol = mergedRegion.getLastColumn(); for (int row = firstRow; row <= lastRow; row++) for (int col = firstCol; col <= lastCol; col++) sheet.getRow(row).getCell(col).setCellStyle(resultStyle); // cell includes only in one merged region break; } } } } }
From source file:com.haulmont.yarg.formatters.impl.xls.hints.CustomWidthHint.java
License:Apache License
@Override public void apply() { for (DataObject dataObject : data) { HSSFCell resultCell = dataObject.resultCell; HSSFCell templateCell = dataObject.templateCell; String templateCellValue = templateCell.getStringCellValue(); Matcher matcher = pattern.matcher(templateCellValue); if (matcher.find()) { String paramName = matcher.group(1); Integer width = (Integer) dataObject.bandData.getParameterValue(paramName); if (width != null) { resultCell.getSheet().setColumnWidth(resultCell.getColumnIndex(), width); }/*from ww w . j a v a2 s . c o m*/ } } }
From source file:com.hl7.main.ImportDataFromXLStoXML.java
public void displayFromExcel(String xlsPath) { InputStream inputStream = null; try {// ww w . j av a 2s . c o m inputStream = new FileInputStream(xlsPath); } catch (FileNotFoundException e) { System.out.println("File not found in the specified path."); e.printStackTrace(); } POIFSFileSystem fileSystem = null; try { // Initializing the XML document DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element rootElement = document.createElement("categories"); document.appendChild(rootElement); fileSystem = new POIFSFileSystem(inputStream); HSSFWorkbook workBook = new HSSFWorkbook(fileSystem); Integer count = workBook.getNumberOfSheets(); ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>(); for (int i = 0; i < count; i++) { HSSFSheet sheet = workBook.getSheetAt(i); Iterator<?> rows = sheet.rowIterator(); while (rows.hasNext()) { HSSFRow row = (HSSFRow) rows.next(); Iterator<?> cells = row.cellIterator(); ArrayList<String> rowData = new ArrayList<String>(); while (cells.hasNext()) { HSSFCell cell = (HSSFCell) cells.next(); String richTextString = cell.getStringCellValue(); System.out.println("String: " + richTextString); rowData.add(richTextString); } // end while data.add(rowData); } // end while } int numOfProduct = data.size(); for (int i = 0; i < numOfProduct; i++) { Element productElement = document.createElement("categoryName"); rootElement.appendChild(productElement); int index = 0; for (String s : data.get(i)) { String headerString = data.get(0).get(index); if (data.get(0).get(index).equals("image link")) { headerString = "image_link"; } if (data.get(0).get(index).equals("product type")) { headerString = "product_type"; } Element headerElement = document.createElement(headerString); productElement.appendChild(headerElement); headerElement.appendChild(document.createTextNode(s)); index++; } } TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); // Add indentation to output transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(new File("products.xml")); // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } catch (IOException e) { System.out.println("IOException " + e.getMessage()); } catch (ParserConfigurationException e) { System.out.println("ParserConfigurationException " + e.getMessage()); } catch (TransformerConfigurationException e) { System.out.println("TransformerConfigurationException " + e.getMessage()); } catch (TransformerException e) { System.out.println("TransformerException " + e.getMessage()); } }
From source file:com.hp.excelhandle.GetData.java
public void readExcel() { try {/*from ww w. j a va 2 s .c o m*/ POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("database/customer.xls")); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); HSSFRow row; HSSFCell cell; int rows; // No of rows rows = sheet.getPhysicalNumberOfRows(); int cols = 0; // No of columns (max) int tmp = 0; // This trick ensures that we get the data properly even if it doesn't start from first few rows for (int i = 0; i < 10 || i < rows; i++) { row = sheet.getRow(i); if (row != null) { tmp = sheet.getRow(i).getPhysicalNumberOfCells(); if (tmp > cols) cols = tmp; } } // for(int r = 0; r < rows; r++) { // row = sheet.getRow(r); // if(row != null) { // for(int c = 0; c < cols; c++) { // cell = row.getCell((short)c); // if(cell != null) { // // Your code here // } // } // } // } row = sheet.getRow(8); if (row != null) { cell = row.getCell(1); if (cell != null) System.out.println("Row: " + 9 + ", Data: " + cell.getStringCellValue()); } } catch (Exception ioe) { ioe.printStackTrace(); } }
From source file:com.ibm.asset.trails.service.impl.CauseCodeServiceImpl.java
@Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW) public ByteArrayOutputStream loadSpreadsheet(File file, String remoteUser, List<State> steps) throws IOException { ByteArrayOutputStream bos = null; FileInputStream fin = new FileInputStream(file); HSSFWorkbook wb = new HSSFWorkbook(fin); HSSFSheet sheet = wb.getSheetAt(0);/* w ww . j av a 2s. c o m*/ HSSFCell reportNameCell = sheet.getRow(ROW_ALERT_TYPE).getCell(COL_ALERT_TYPE); String reportName = reportNameCell.getStringCellValue().trim(); HSSFCellStyle errorStyle = wb.createCellStyle(); errorStyle.setFillForegroundColor(HSSFColor.RED.index); errorStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); colIndexes = ECauseCodeReport.getReportByName(reportName); boolean error = validateExcelCauseCodeContent(sheet, errorStyle, steps); if (!error) { saveCauseCode(wb, remoteUser, steps); } else { State state = State.findStateByLable(steps, STEP3_LABEL); if (state == null) { state = new State(); state.setDescription("Persist changes"); state.setLabel(STEP3_LABEL); state.setStatus(EStatus.IGNORED); steps.add(state); } } bos = new ByteArrayOutputStream(); wb.write(bos); return bos; }
From source file:com.ibm.asset.trails.service.impl.CauseCodeServiceImpl.java
@SuppressWarnings("unchecked") private boolean validateExcelCauseCodeContent(HSSFSheet sheet, HSSFCellStyle errorStyle, List<State> steps) { State state = State.findStateByLable(steps, STEP2_LABEL); if (state == null) { state = new State(); state.setDescription("Data validation"); state.setLabel(STEP2_LABEL);/*www. jav a 2s. c om*/ state.setStatus(EStatus.IN_PROGRESS); steps.add(state); } boolean error = false; if (colIndexes == null) { int lastCellNO = sheet.getRow(ROW_ALERT_TYPE).getLastCellNum(); HSSFCell cell = sheet.getRow(ROW_ALERT_TYPE).createCell(lastCellNO + 1); cell.setCellStyle(errorStyle); cell.setCellValue(new HSSFRichTextString(ERROR_UNKONW_TYPE)); error = true; } else { Iterator<Row> rowIter = sheet.rowIterator(); int rowCounter = -1; int totalRows = sheet.getLastRowNum(); int colStart = colIndexes.getColCauseCode(); int colEnd = colIndexes.getColInternalId(); while (rowIter.hasNext()) { HSSFRow row = (HSSFRow) rowIter.next(); rowCounter++; int progress = (int) ((float) rowCounter / totalRows * 100); state.setProgress(progress); if (rowCounter <= ROW_TABLE_HEAD) { continue; } StringBuffer errorMsg = new StringBuffer(); for (int col = colStart; col <= colEnd; col++) { HSSFCell cell = row.getCell(col); if (col == colIndexes.getColInternalId()) { if (!isCauseCodeExists(cell)) { buildErrorMsg(errorMsg, colIndexes.getColInternalId(), "Internal ID", ERROR_INTERNAL_ID_NOT_EXIST); } else { Long alertTypeId = getAlertTypeId(cell); if (alertTypeId != null && alertTypeId != this.getAlertTypeIdByCode(colIndexes.getAlertTypeCode())) { buildErrorMsg(errorMsg, colIndexes.getColInternalId(), "Internal ID", ERROR_ALERT_TYPE_NOT_MATCH); } } } if (col == colIndexes.getColCauseCode()) { if (cell == null) { buildErrorMsg(errorMsg, colIndexes.getColCauseCode(), "Cause Code (CC)", ERROR_UNKONW_CAUSE_CODE); continue; } HSSFCell causeCodeIdCell = row.getCell(colIndexes.getColInternalId()); if (!isCauseCodeExists(causeCodeIdCell)) { buildErrorMsg(errorMsg, colIndexes.getColCauseCode(), "Cause Code (CC)", ERROR_UNKONW_CAUSE_CODE); continue; } boolean pass = true; // if no change continue; String alertCauseNameInCell = null; if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) { alertCauseNameInCell = cell.getStringCellValue(); } else { pass = false; } if (alertCauseNameInCell == null || "".equals(alertCauseNameInCell.trim())) { pass = false; } if (!pass) { buildErrorMsg(errorMsg, colIndexes.getColCauseCode(), "Cause Code (CC)", ERROR_UNKONW_CAUSE_CODE); continue; } if (alertCauseNameInCell.length() > 128) { alertCauseNameInCell = alertCauseNameInCell.substring(0, 128); } String alertCauseNameInDb = getAlertCauseName(causeCodeIdCell); // compare the cc name and cause code name under id. if // not same check it's availability. if same ignore. if (!strCompare(alertCauseNameInDb, alertCauseNameInCell)) { List<AlertCause> acList = null; try { acList = getEntityManager().createNamedQuery("findActiveAlertCauseByNameAndTypeId") .setParameter("alertCauseName", alertCauseNameInCell.trim().toUpperCase()) .setParameter("alertTypeId", this.getAlertTypeIdByCode(colIndexes.getAlertTypeCode())) .getResultList(); if (acList.size() <= 0) { buildErrorMsg(errorMsg, colIndexes.getColCauseCode(), "Cause Code (CC)", ERROR_UNKONW_CAUSE_CODE); } } catch (Exception e) { log.error(e.getMessage(), e); } } } if (col == colIndexes.getColTargetDate()) { if (!isDateFormat(cell)) {//CC Target Date is an optional field buildErrorMsg(errorMsg, colIndexes.getColTargetDate(), "CC target date", ERROR_BAD_DATE_FORMAT); } } if (col == colIndexes.getColOwner()) { if (!isOwnerExistsInBluePage(cell)) {//CC Owner is an optional field buildErrorMsg(errorMsg, colIndexes.getColOwner(), "CC owner", ERROR_UNKNOW_OWNER); } } } if (errorMsg.length() > 0) { HSSFCell msgCell = row.createCell(colIndexes.getColMessage()); msgCell.setCellStyle(errorStyle); msgCell.setCellValue(new HSSFRichTextString(errorMsg.toString())); error = true; } } } if (error) { state.setStatus(EStatus.FAILED); } else { if (state.getProgress() == 100 && state.getStatus().getPriority() < EStatus.FINISHED.getPriority()) { state.setStatus(EStatus.FINISHED); } } return error; }
From source file:com.ibm.asset.trails.service.impl.CauseCodeServiceImpl.java
private void saveCauseCode(HSSFWorkbook wb, String remoteUser, List<State> steps) { HSSFSheet sheet = wb.getSheetAt(0);//from ww w . j av a2 s . c o m Iterator<Row> rowIter = sheet.rowIterator(); State state = State.findStateByLable(steps, STEP3_LABEL); if (state == null) { state = new State(); state.setDescription("Persist changes"); state.setLabel(STEP3_LABEL); state.setStatus(EStatus.IN_PROGRESS); steps.add(state); } int rowCounter = -1; int totalRows = sheet.getLastRowNum(); while (rowIter.hasNext()) { HSSFRow row = (HSSFRow) rowIter.next(); rowCounter++; int progress = (int) ((float) rowCounter / totalRows * 100); state.setProgress(progress); if (progress == 100) { state.setStatus(EStatus.FINISHED); } if (rowCounter <= ROW_TABLE_HEAD) { continue; } HSSFCell causeCodeIdCell = row.getCell(colIndexes.getColInternalId()); long causeCodeId = -1; if (causeCodeIdCell.getCellType() == HSSFCell.CELL_TYPE_STRING) { causeCodeId = Long.valueOf(causeCodeIdCell.getStringCellValue()); } else if (causeCodeIdCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) { causeCodeId = Math.round(causeCodeIdCell.getNumericCellValue()); } CauseCode causeCode = (CauseCode) getEntityManager().createNamedQuery("getCauseCodeById") .setParameter("id", causeCodeId).getSingleResult(); String causeCodeName = causeCode.getAlertCause().getName(); HSSFCell causeCodeCell = row.getCell(colIndexes.getColCauseCode()); String colCauseCode = null; if (causeCodeCell != null) { colCauseCode = causeCodeCell.getStringCellValue().trim(); } Date targetDate = causeCode.getTargetDate(); HSSFCell targetDateCell = row.getCell(colIndexes.getColTargetDate()); Date colTargetDate = null; if (targetDateCell != null) { if (targetDateCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC && HSSFDateUtil.isCellDateFormatted(targetDateCell)) { colTargetDate = targetDateCell.getDateCellValue(); } else if (targetDateCell.getCellType() == HSSFCell.CELL_TYPE_STRING) { colTargetDate = convertTextToDate(targetDateCell);//Convert Date Text to Date Object } } String owner = causeCode.getOwner(); HSSFCell ownerCell = row.getCell(colIndexes.getColOwner()); String colOwner = null; if (ownerCell != null) { colOwner = ownerCell.getStringCellValue().trim(); } //Assignee Comments Function Start if (colIndexes.getColAssigneeComments() != -1) { HSSFCell assigneeCommentsCell = row.getCell(colIndexes.getColAssigneeComments()); String assigneeComments = ""; if (assigneeCommentsCell != null && assigneeCommentsCell.getCellType() == HSSFCell.CELL_TYPE_STRING) { assigneeComments = assigneeCommentsCell.getStringCellValue(); } if (assigneeComments != null && !"".equals(assigneeComments.trim())) { updateAssigneeComments(causeCode.getAlertId(), assigneeComments.trim(), colIndexes.getReportName().trim(), remoteUser); } } //Assignee Comments Function End boolean changed = false; if (!strCompare(causeCodeName, colCauseCode) || !dateCompare(targetDate, colTargetDate) || !strCompare(owner, colOwner)) { changed = true; } if (!changed) { continue; } CauseCodeHistory history = new CauseCodeHistory(); history.setCauseCode(causeCode); history.setAlertType(causeCode.getAlertType()); history.setAlertId(causeCode.getAlertId()); history.setAlertCause(causeCode.getAlertCause()); history.setTargetDate(causeCode.getTargetDate()); history.setOwner(causeCode.getOwner()); history.setRecordTime(causeCode.getRecordTime()); history.setRemoteUser(causeCode.getRemoteUser()); if (!strCompare(causeCodeName, colCauseCode)) { try { AlertCause alertCause = null; if ("UNDEFINED".equals(colCauseCode.trim().toUpperCase())) { alertCause = (AlertCause) getEntityManager() .createNamedQuery("findAlertCauseByNameWithoutShowInGui") .setParameter("name", colCauseCode.trim().toUpperCase()).getSingleResult(); } else { alertCause = (AlertCause) getEntityManager().createNamedQuery("findAlertCauseByName") .setParameter("name", colCauseCode.trim().toUpperCase()).getSingleResult(); } if (alertCause != null) { causeCode.setAlertCause(alertCause); } } catch (Exception e) { log.error(e.getMessage(), e); } } if (!dateCompare(targetDate, colTargetDate)) { causeCode.setTargetDate(colTargetDate); } if (!strCompare(owner, colOwner)) { causeCode.setOwner(colOwner); } causeCode.setRemoteUser(remoteUser); causeCode.setRecordTime(new Date()); try { getEntityManager().persist(history); getEntityManager().persist(causeCode); getEntityManager().flush(); } catch (Exception e) { log.error(e.getMessage(), e); } } }
From source file:com.ibm.asset.trails.service.impl.CauseCodeServiceImpl.java
private boolean isOwnerExistsInBluePage(HSSFCell cell) { if (cell == null) { return true; }//from w w w . j av a 2 s . c o m if (cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) { return true; } if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) { String internetId = cell.getStringCellValue(); if (internetId == null || "".equals(internetId.trim())) { return true; } BPResults result = BluePages.getPersonsByInternet(internetId); return result.hasColumn("EMPNUM"); } return false; }
From source file:com.ibm.asset.trails.service.impl.CauseCodeServiceImpl.java
private boolean isDateFormat(HSSFCell cell) { if (cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) { return true; }/*from ww w . java 2s. c om*/ if (cell.getCellType() == HSSFCell.CELL_TYPE_ERROR) { return true; } if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) { String dateStr = cell.getStringCellValue(); if (dateStr == null || "".equals(dateStr.trim())) { return true; } else { dateStr = dateStr.trim(); int dateLen = dateStr.length(); if (dateLen != 10) { return false; } else { boolean dashFormat = dateStr.indexOf(DASH) != -1; if (dashFormat) {//DASH Date Format: YYYY-MM-DD SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT1); try { format.setLenient(false); format.parse(dateStr); return true; } catch (ParseException e) { return false; } } else { SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT2);//SLASH Date Format: YYYY/MM/DD try { format.setLenient(false); format.parse(dateStr); return true; } catch (ParseException e) { format = new SimpleDateFormat(DATE_FORMAT3);//SLASH Date Format: MM/DD/YYYY try { format.setLenient(false); format.parse(dateStr); return true; } catch (ParseException ex) { return false; } } } } } } if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC && HSSFDateUtil.isCellDateFormatted(cell)) { return true; } return false; }