List of usage examples for org.apache.poi.ss.usermodel Cell getDateCellValue
Date getDateCellValue();
From source file:com.dituiba.excel.DefaultInputAdapter.java
License:Apache License
/** * ?/*from ww w . j a v a 2 s . co m*/ * * @param type * @param fieldName * @param cell * @throws IllegalAccessException * @throws ParseException */ public Object inputDateAdapter(DataBean dataBean, Class type, String fieldName, Cell cell) throws AdapterException { log.debug("in DefaultInputAdapter:inputDateAdapter fieldName:{} type:{}", fieldName, type.getSimpleName()); InputDateConfig inputDateConfig = dataBean.getInputConfig(fieldName); Object o = null; if (Cell.CELL_TYPE_BLANK == cell.getCellType()) { log.debug("cell is blank "); return o; } else if (Date.class.isAssignableFrom(type)) { if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) { Date date = cell.getDateCellValue(); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int i = calendar.get(Calendar.YEAR); try { //???2014026?? o = i > 2500 ? DateUtil.formatToDate(String.format("%.0f", cell.getNumericCellValue()), inputDateConfig.format()) : date; } catch (ParseException e) { throw new AdapterException(fieldName, Message.DATE_TYPE_ERROR, cell); } } else if (Cell.CELL_TYPE_STRING == cell.getCellType()) { try { o = DateUtil.formatToDate(trim(cell.getStringCellValue()), inputDateConfig.format()); } catch (ParseException e) { throw new AdapterException(fieldName, Message.DATE_TYPE_ERROR, cell); } } else if (Cell.CELL_TYPE_BLANK == cell.getCellType()) { return null; } else { throw new AdapterException(fieldName, Message.DATE_TYPE_ERROR, cell); } } else if (String.class.isAssignableFrom(type)) { if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) { Date dateCellValue = cell.getDateCellValue(); o = DateUtil.format(dateCellValue, inputDateConfig.format()); } else if (Cell.CELL_TYPE_STRING == cell.getCellType()) { OutputDateConfig outputDateConfig = dataBean.getOutputConfig(fieldName); try { o = DateUtil.format(trim(cell.getStringCellValue()), outputDateConfig.format(), inputDateConfig.format()); } catch (ParseException e) { throw new AdapterException(fieldName, Message.DATE_TYPE_ERROR, cell); } } else { throw new AdapterException(fieldName, Message.DATE_TYPE_ERROR, cell); } } else { throw new AdapterException(fieldName, Message.DATE_TYPE_ERROR, cell); } return o; }
From source file:com.dituiba.excel.DefaultInputAdapter.java
License:Apache License
public static Object getCellValue(Cell cell, Class type) throws AdapterException { if (cell == null) return ""; try {/* w ww .j a v a 2s .com*/ switch (cell.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: return cell.getBooleanCellValue(); case Cell.CELL_TYPE_BLANK: return ""; case Cell.CELL_TYPE_NUMERIC: if (String.class.isAssignableFrom(type)) { cell.setCellType(Cell.CELL_TYPE_STRING); return trim(cell.getStringCellValue()); } else if (Date.class.isAssignableFrom(type)) { return cell.getDateCellValue(); } return cell.getNumericCellValue(); case Cell.CELL_TYPE_STRING: return trim(cell.getStringCellValue()); case Cell.CELL_TYPE_FORMULA: try { return String.valueOf(cell.getNumericCellValue()); } catch (IllegalStateException e) { return trim(String.valueOf(cell.getRichStringCellValue())); } } } catch (Exception e) { throw new AdapterException(Message.INPUT_CELL_DATA_ERROR, cell); } throw new AdapterException(Message.INPUT_CELL_DATA_ERROR, cell); }
From source file:com.dituiba.excel.ExcelUtility.java
License:Apache License
public static void copyCell(Cell srcCell, Cell distCell) { distCell.setCellStyle(srcCell.getCellStyle()); if (srcCell.getCellComment() != null) { distCell.setCellComment(srcCell.getCellComment()); }//from w w w. j a v a 2 s . c om int srcCellType = srcCell.getCellType(); distCell.setCellType(srcCellType); if (srcCellType == Cell.CELL_TYPE_NUMERIC) { if (DateUtil.isCellDateFormatted(srcCell)) { distCell.setCellValue(srcCell.getDateCellValue()); } else { distCell.setCellValue(srcCell.getNumericCellValue()); } } else if (srcCellType == Cell.CELL_TYPE_STRING) { distCell.setCellValue(srcCell.getRichStringCellValue()); } else if (srcCellType == Cell.CELL_TYPE_BLANK) { //nothing } else if (srcCellType == Cell.CELL_TYPE_BOOLEAN) { distCell.setCellValue(srcCell.getBooleanCellValue()); } else if (srcCellType == Cell.CELL_TYPE_ERROR) { distCell.setCellErrorValue(srcCell.getErrorCellValue()); } else if (srcCellType == Cell.CELL_TYPE_FORMULA) { distCell.setCellFormula(srcCell.getCellFormula()); } else { //nothing } }
From source file:com.dituiba.excel.ImportTableService.java
License:Apache License
/** * ExcelTableBean// w ww.j av a 2 s .c om */ public void doImport() { int rowNum = sheet.getLastRowNum() + 1; int columnNum = 0; for (int i = 0; i < rowNum; i++) { if (sheet.getRow(i) != null) { int last = sheet.getRow(i).getLastCellNum(); columnNum = last > columnNum ? last : columnNum; } } tableBean = new TableBean(rowNum, columnNum); Collection<CellBean> cellBeans = new ArrayList<CellBean>(); for (int r = startRow; r < rowNum; r++) { Row row = sheet.getRow(r); if (row != null) { for (int c = 0; c < row.getLastCellNum(); c++) { Cell cell = row.getCell(c); if (cell != null) { String cellValue = null; if (cellHandlerMap.containsKey(c)) { cellValue = cellHandlerMap.get(c).readCell(cell) + ""; } else { cell.setCellType(Cell.CELL_TYPE_STRING); Integer type = forceCellType.get(c); if (type != null) { cell.setCellType(type); } if (Cell.CELL_TYPE_BOOLEAN == cell.getCellType()) { cellValue = cell.getBooleanCellValue() + ""; } else if (Cell.CELL_TYPE_FORMULA == cell.getCellType()) { try { cellValue = String.valueOf(cell.getNumericCellValue()); } catch (IllegalStateException e) { cellValue = String.valueOf(cell.getRichStringCellValue()).trim(); } } else if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) { if (DateUtil.isCellDateFormatted(cell)) { Date date2 = cell.getDateCellValue(); SimpleDateFormat dff = new SimpleDateFormat(dateFormat); cellValue = dff.format(date2); // } else { cellValue = String.valueOf(cell.getNumericCellValue()); } } else if (Cell.CELL_TYPE_STRING == cell.getCellType()) { cellValue = cell.getStringCellValue(); } if (cellValue != null && cellValue instanceof String) { cellValue = cellValue.toString().trim(); } } CellBean cellBean = new CellBean(cellValue, r, c); cellBean.setCell(cell); cellBeans.add(cellBean); } } } } tableBean.setCellBeans(cellBeans); }
From source file:com.Excel.Excel.java
private void leerArchivo(int indiceHoja) { abrirArchivo();//from ww w . j a v a 2 s. c om this.datos = new HashMap<>(); HSSFSheet sheet = workbook.getSheetAt(indiceHoja); Iterator<Row> rowIterator = sheet.iterator(); int fila = 0; Row row; while (rowIterator.hasNext()) { List<Object> datosFila = new ArrayList<>(); Cell celda; row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Object dato = null; celda = cellIterator.next(); switch (celda.getCellType()) { case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(celda)) { System.out.print(celda.getDateCellValue()); dato = celda.getDateCellValue(); } else { System.out.print(celda.getNumericCellValue()); dato = celda.getNumericCellValue(); } break; case Cell.CELL_TYPE_STRING: System.out.print(celda.getStringCellValue()); dato = celda.getStringCellValue(); break; case Cell.CELL_TYPE_BOOLEAN: System.out.print(celda.getBooleanCellValue()); dato = celda.getBooleanCellValue(); break; } datosFila.add(dato); } datos.put(fila++, datosFila); System.out.println(""); } cerrarArchivo(); }
From source file:com.Excel.Excel2007.java
private void leerArchivo(int indiceHoja) { abrirArchivo();// w ww .j a v a 2s.c o m this.datos = new HashMap<>(); XSSFSheet sheet = workbook.getSheetAt(indiceHoja); Iterator<Row> rowIterator = sheet.iterator(); int fila = 0; Row row; while (rowIterator.hasNext()) { List<Object> datosFila = new ArrayList<>(); Cell celda; row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Object dato = null; celda = cellIterator.next(); switch (celda.getCellType()) { case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(celda)) { System.out.print(celda.getDateCellValue()); dato = celda.getDateCellValue(); } else { System.out.print(celda.getNumericCellValue()); dato = celda.getNumericCellValue(); } break; case Cell.CELL_TYPE_STRING: System.out.print(celda.getStringCellValue()); dato = celda.getStringCellValue(); break; case Cell.CELL_TYPE_BOOLEAN: System.out.print(celda.getBooleanCellValue()); dato = celda.getBooleanCellValue(); break; } datosFila.add(dato); } datos.put(fila++, datosFila); System.out.println(""); } cerrarArchivo(); }
From source file:com.exilant.exility.core.XLSReader.java
License:Open Source License
/** * purpose of this method to create ValueList along with types and column * name. Simple design followed : Just have ColumnMetaData object which * contains everything. For a Cell we will have one columnMetaData object * and it will have values across the//from ww w . j a va 2 s . co m * * @param row * @throws Exception */ private void readARow(Row row, int nbrColumnsInARow) throws ExilityException { Value[] columnValues = new Value[nbrColumnsInARow]; Value aColumnValue = null; String rawValue = null; for (int c = 0; c < nbrColumnsInARow; c++) { Cell cell = row.getCell(c, Row.CREATE_NULL_AS_BLANK); ColumnMetaData columnInfo = this.columnsData.get(new Integer(c)); int xlsColumnDataType = columnInfo.getXlsDataType(); DataValueType exilDataType = null; int cellType = cell.getCellType(); if (xlsColumnDataType != XLSReader.UNKNOWN_TYPE) { cellType = xlsColumnDataType; } try { switch (cellType) { case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { rawValue = DateUtility.formatDate(cell.getDateCellValue()); /* * returns yyyy-mm-dd hh:mm:ss.sss full date with time. */ exilDataType = DataValueType.DATE; } else { double decimalNumber = cell.getNumericCellValue(); rawValue = NumberToTextConverter.toText(decimalNumber); boolean isDecimal = rawValue.contains("."); if (isDecimal) { exilDataType = DataValueType.DECIMAL; } else { exilDataType = DataValueType.INTEGRAL; } } break; case Cell.CELL_TYPE_STRING: rawValue = cell.getStringCellValue().trim(); exilDataType = DataValueType.TEXT; break; case Cell.CELL_TYPE_FORMULA: rawValue = cell.getStringCellValue().trim(); exilDataType = DataValueType.TEXT; break; case Cell.CELL_TYPE_BLANK: rawValue = cell.getStringCellValue(); exilDataType = DataValueType.NULL; columnInfo.setExilDataType(exilDataType); break; case Cell.CELL_TYPE_BOOLEAN: rawValue = cell.getBooleanCellValue() ? BooleanValue.TRUE : BooleanValue.FALSE; exilDataType = DataValueType.BOOLEAN; break; default: String msg = columnInfo.getColumnName() + XLSReader.INVALID_COLUMN_TYPE + row.getRowNum(); Spit.out(msg); } } catch (Exception e) { // Trying to set valueType value and expected valueType value // for column in row String[] params = { this.getXlsTypeAsText(cell.getCellType()), this.getXlsTypeAsText(cellType), columnInfo.getColumnName(), "" + row.getRowNum() }; String message = this.replaceMessageParams(XLSReader.DATATYPE_MISMATCH, params); throw new ExilityException(message); } if (xlsColumnDataType == XLSReader.UNKNOWN_TYPE && cellType != Cell.CELL_TYPE_BLANK) { columnInfo.setXlsDataType(cellType); columnInfo.setExilDataType(exilDataType); } exilDataType = columnInfo.getExilDataType(); aColumnValue = Value.newValue(rawValue, exilDataType); columnValues[c] = aColumnValue; this.columnsData.put(new Integer(c), columnInfo); } this.rows.add(columnValues); }
From source file:com.exilant.exility.core.XlxUtil.java
License:Open Source License
/*** * get text value of cell irrespective of its content type * /* ww w . ja v a2s. co m*/ * @param cell * @return */ private String getTextValue(Cell cell) { if (cell == null) { return EMPTY_STRING; } int cellType = cell.getCellType(); if (cellType == Cell.CELL_TYPE_BLANK) { return EMPTY_STRING; } if (cellType == Cell.CELL_TYPE_FORMULA) { cellType = cell.getCachedFormulaResultType(); } if (cellType == Cell.CELL_TYPE_STRING) { return cell.getStringCellValue().trim(); } /* * dates are internally stored as decimal.. */ if (cellType == Cell.CELL_TYPE_NUMERIC) { if (DateUtil.isCellDateFormatted(cell)) { return DateUtility.formatDate(cell.getDateCellValue()); } return NumberFormat.getInstance().format(cell.getNumericCellValue()); } if (cellType == Cell.CELL_TYPE_BOOLEAN) { if (cell.getBooleanCellValue()) { return "1"; } return "0"; } return EMPTY_STRING; }
From source file:com.femsa.kof.csi.util.XlsAnalizer.java
/** * Mtodo encargado de la lectura y anlisis de una hoja del archivo excel * cargado en la interfaz grfica correspondiente a Rolling * * * @param rowIterator lista de renglones contenidos en la hoja de excel * @param usuario usuario que realiza el anlisis * @param sheetName nombre de la hoja de excel * @return Regresa una lista con los registros a ser almacenados en base de * datos/*from w w w . jav a2s.c o m*/ */ private List<Xtmpinddl> analizeSheetIndi(Iterator<Row> rowIterator, DcsUsuario usuario, String sheetName, List<DcsCatPais> paises, List<DcsCatIndicadores> indicadores) throws DCSException { int numRow = 0; List<Xtmpinddl> cargas = new ArrayList<Xtmpinddl>(); Xtmpinddl indi; SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Calendar calendarioActual = Calendar.getInstance(); Calendar calendario = Calendar.getInstance(); end: while (rowIterator != null && rowIterator.hasNext()) { Row row = rowIterator.next(); Cell cell; if (numRow == 0) { } else { indi = new Xtmpinddl(); cell = row.getCell(0); if (cell != null && cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { calendario.setTime(cell.getDateCellValue()); if ("User".equalsIgnoreCase(usuario.getFkIdRol().getRol()) && (calendarioActual.get(Calendar.YEAR) != calendario.get(Calendar.YEAR) || calendarioActual.get(Calendar.MONTH) != calendario.get(Calendar.MONTH))) { throw new DCSException( "Error: You can not load information of a different month of the current"); } indi.setFecha(sdf.format(cell.getDateCellValue())); } else if (cell != null && cell.getCellType() == Cell.CELL_TYPE_STRING) { try { calendario.setTime(sdf.parse(cell.getStringCellValue().trim())); if ("User".equalsIgnoreCase(usuario.getFkIdRol().getRol()) && (calendarioActual .get(Calendar.YEAR) != calendario.get(Calendar.YEAR) || calendarioActual.get(Calendar.MONTH) != calendario.get(Calendar.MONTH))) { throw new DCSException( "Error: You can not load information of a different month of the current"); } indi.setFecha(cell.getStringCellValue().trim()); } catch (ParseException ex) { Logger.getLogger(XlsAnalizer.class.getName()).log(Level.SEVERE, null, ex); errors.add("Approximately " + Character.toString((char) (65 + 0)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "]."); cargas.clear(); break; } } else { numRow++; continue; } cell = row.getCell(1); if (cell == null || cell.getCellType() == Cell.CELL_TYPE_STRING) { indi.setGrupoInd(cell != null ? cell.getStringCellValue().trim() : null); } else { errors.add("Approximately " + Character.toString((char) (65 + 1)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "]."); cargas.clear(); break; } cell = row.getCell(2); if (cell == null || cell.getCellType() == Cell.CELL_TYPE_STRING) { if (indicadores.contains( new DcsCatIndicadores(cell != null ? cell.getStringCellValue().trim() : null))) { indi.setIndicador(cell != null ? cell.getStringCellValue().trim() : null); } else { errors.add("Approximately " + Character.toString((char) (65 + 2)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "], indicator not found."); cargas.clear(); break; } } else { errors.add("Approximately " + Character.toString((char) (65 + 2)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "]."); cargas.clear(); break; } cell = row.getCell(3); if (cell != null && cell.getCellType() == Cell.CELL_TYPE_STRING) { if ("KOF".equalsIgnoreCase(cell.getStringCellValue().trim()) || paises.contains(new DcsCatPais(cell.getStringCellValue().trim()))) { indi.setPais(cell.getStringCellValue().trim()); } else { errors.add("Approximately " + Character.toString((char) (65 + 3)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "]."); cargas.clear(); break; } if ("User".equalsIgnoreCase(usuario.getFkIdRol().getRol()) && (!usuario.getPais().equalsIgnoreCase(indi.getPais()))) { throw new DCSException("Error: you can not load information from other country"); } } else { errors.add("Approximately " + Character.toString((char) (65 + 3)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "]."); cargas.clear(); break; } cell = row.getCell(4); if (cell == null || cell.getCellType() == Cell.CELL_TYPE_STRING || cell.getCellType() == Cell.CELL_TYPE_BLANK) { indi.setCentro(cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK ? cell.getStringCellValue().trim() : null); } else { errors.add("Approximately " + Character.toString((char) (65 + 4)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "]."); cargas.clear(); break; } cell = row.getCell(5); if (cell == null || cell.getCellType() == Cell.CELL_TYPE_STRING || cell.getCellType() == Cell.CELL_TYPE_BLANK) { indi.setRuta(cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK ? cell.getStringCellValue().trim() : null); } else { errors.add("Approximately " + Character.toString((char) (65 + 5)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "]."); cargas.clear(); break; } cell = row.getCell(6); if (cell == null || cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { indi.setValorMensual(cell != null ? (float) cell.getNumericCellValue() : 0); } else { errors.add("Approximately " + Character.toString((char) (65 + 6)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "]."); cargas.clear(); break; } cell = row.getCell(7); if (cell == null || cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { indi.setValorAcumulado(cell != null ? (float) cell.getNumericCellValue() : 0); } else { errors.add("Approximately " + Character.toString((char) (65 + 7)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "]."); cargas.clear(); break; } cargas.add(indi); } numRow++; } return cargas; }
From source file:com.fjn.helper.common.io.file.office.excel.ListExcelSheetReader.java
License:Apache License
private <T> T getBean(Class<T> clazz, Row row, List<String> fieldList) { Field[] fields = new Field[fieldList.size()]; for (int i = 0; i < fields.length; i++) { Field field = null;/* w ww.j a va 2 s. c om*/ try { field = clazz.getDeclaredField(fieldList.get(i)); // field.getAnnotation(); fields[i] = field; field.setAccessible(true); } catch (Exception e) { e.printStackTrace(); } } T t = null; try { t = clazz.newInstance(); } catch (Exception e) { e.printStackTrace(); } for (int i = 0; i < fields.length; i++) { Cell cell = null; cell = row.getCell(i); if (cell != null) { int cellType = cell.getCellType(); Object value = null; switch (cellType) { case Cell.CELL_TYPE_STRING: value = cell.getRichStringCellValue().getString(); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { value = cell.getDateCellValue(); } else { value = cell.getNumericCellValue(); Class fieldClass = fields[i].getType(); if (fieldClass == Integer.class || fieldClass == int.class) { value = ((Double) value).intValue(); } else if (fieldClass == Short.class || fieldClass == short.class) { value = ((Double) value).shortValue(); } else if (fieldClass == Byte.class || fieldClass == byte.class) { value = ((Double) value).byteValue(); } else if (fieldClass == Long.class || fieldClass == long.class) { value = ((Double) value).longValue(); } else if (fieldClass == Float.class || fieldClass == float.class) { value = ((Double) value).floatValue(); } else if (fieldClass == Double.class || fieldClass == double.class) { value = (Double) value; } } break; case Cell.CELL_TYPE_BOOLEAN: value = cell.getBooleanCellValue(); break; case Cell.CELL_TYPE_FORMULA: value = cell.getCellFormula(); break; default: break; } try { fields[i].set(t, value); } catch (Exception e) { e.printStackTrace(); } } } return t; }