Example usage for org.apache.poi.ss.usermodel Cell getDateCellValue

List of usage examples for org.apache.poi.ss.usermodel Cell getDateCellValue

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel Cell getDateCellValue.

Prototype

Date getDateCellValue();

Source Link

Document

Get the value of the cell as a date.

Usage

From source file:com.qihang.winter.poi.excel.imports.CellValueServer.java

License:Apache License

/**
 * ??//from  ww  w .  j a  v  a  2s  .c o m
 * 
 * @param xclass
 * @param cell
 * @param entity
 * @return
 */
private Object getCellValue(String xclass, Cell cell, ExcelImportEntity entity) {
    if (cell == null) {
        return "";
    }
    Object result = null;
    // ?,cell??
    if ("class java.util.Date".equals(xclass) || ("class java.sql.Time").equals(xclass)) {
        if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {
            // ?
            result = cell.getDateCellValue();
        } else {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            result = getDateData(entity, cell.getStringCellValue());
        }
        if (("class java.sql.Time").equals(xclass)) {
            result = new Time(((Date) result).getTime());
        }
    } else if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {
        result = cell.getNumericCellValue();
    } else if (Cell.CELL_TYPE_BOOLEAN == cell.getCellType()) {
        result = cell.getBooleanCellValue();
    } else {
        result = cell.getStringCellValue();
    }
    return result;
}

From source file:com.rapidminer.operator.nio.Excel2007SheetTableModel.java

License:Open Source License

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    Cell cell;
    if (config != null) {
        Row row = sheet.getRow(rowIndex + config.getRowOffset());
        if (row == null) {
            return null;
        }/*from www .  j a  v  a2 s  . co m*/
        cell = row.getCell(columnIndex + config.getColumnOffset());
    } else {
        Row row = sheet.getRow(rowIndex);
        if (row == null) {
            return null;
        }
        cell = row.getCell(columnIndex);
    }
    if (cell == null) {
        return null;
    }
    if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
        return cell.getBooleanCellValue();
    } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
        return cell.getStringCellValue();
    } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
        if (HSSFDateUtil.isCellDateFormatted(cell)) {
            return cell.getDateCellValue();
        } else {
            return cell.getNumericCellValue();
        }
    } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
        return cell.getErrorCellValue();
    } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
        return cell.getNumericCellValue();
    } else {
        // last resort, should not come to this
        // maybe return null?
        return "";
    }
}

From source file:com.rapidminer.operator.nio.model.Excel2007ResultSet.java

License:Open Source License

@Override
public Date getDate(int columnIndex) throws ParseException {
    final Cell cell = getCurrentCell(columnIndex);
    if (cell == null) {
        return null;
    }//from  w w  w  . j  a  v a2  s. c  o m
    if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
        return cell.getDateCellValue();
    } else {
        try {
            String valueString = cell.getStringCellValue();
            try {
                SimpleDateFormat simpleDateFormat = ParameterTypeDateFormat.createCheckedDateFormat(dateFormat,
                        null);
                simpleDateFormat.setTimeZone(TimeZone.getTimeZone(this.timeZone));
                return simpleDateFormat.parse(valueString);
            } catch (java.text.ParseException e) {
                throw new ParseException(new ParsingError(currentRow, columnIndex,
                        ParsingError.ErrorCode.UNPARSEABLE_DATE, valueString));
            } catch (UserError userError) {
                throw new ParseException(new ParsingError(currentRow, columnIndex,
                        ParsingError.ErrorCode.UNPARSEABLE_DATE, userError.getMessage()));
            }
        } catch (IllegalStateException e) {
            throw new ParseException(new ParsingError(currentRow, columnIndex,
                    ParsingError.ErrorCode.UNPARSEABLE_DATE, "CELL_NEITHER_NUMERIC_NOR_NOMINAL"));
        }
    }
}

From source file:com.runwaysdk.dataaccess.io.excel.AttributeColumn.java

License:Open Source License

/**
 * Excel contains several different types of cells, with different getters.
 * This method checks the expected type, calls the appropriate getter on the
 * cell, then wraps the result in the correct java type for use in the
 * typesafe setter methods.//from www.  ja v  a 2s  .  c  om
 * 
 * @param cell
 * @param column
 * @return
 */
public Object getValue(Cell cell) throws Exception {
    String type = this.javaType();

    if (this.isEnum()) {
        String cellValue = ExcelUtil.getString(cell);
        Class<?> enumClass = LoaderDecorator.load(type);

        BusinessEnumeration[] values = (BusinessEnumeration[]) enumClass.getMethod("values").invoke(null);
        for (BusinessEnumeration value : values) {
            if (cellValue.equalsIgnoreCase(value.getDisplayLabel())) {
                return value;
            }
        }

        // We did not find a matching enum value. That is a problem.
        MdAttributeEnumerationDAO mdAttribute = (MdAttributeEnumerationDAO) this.getMdAttribute()
                .getMdAttributeConcrete();
        throw new InvalidEnumerationName("devMessage", cellValue, mdAttribute.getMdEnumerationDAO());
    }

    /*
     * Check for null values
     */
    if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
        return null;
    } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
        switch (cell.getCachedFormulaResultType()) {
        case Cell.CELL_TYPE_STRING:
            String value = cell.getRichStringCellValue().getString();

            if (value == null || value.length() == 0) {
                return null;
            }

            break;
        case Cell.CELL_TYPE_BLANK:
            return null;
        }
    } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
        String value = cell.getRichStringCellValue().getString();

        if (value == null || value.length() == 0) {
            return null;
        }
    }

    if (type.equals(String.class.getName())) {
        return ExcelUtil.getString(cell);
    } else if (type.equals(Long.class.getName())) {
        return new Long(new Double(cell.getNumericCellValue()).longValue());
    } else if (type.equals(Float.class.getName())) {
        return new Float(new Double(cell.getNumericCellValue()).floatValue());
    } else if (type.equals(Double.class.getName())) {
        return new Double(cell.getNumericCellValue());
    } else if (type.equals(BigDecimal.class.getName())) {
        return new BigDecimal(cell.getNumericCellValue());
    } else if (type.equals(Integer.class.getName())) {
        return new Integer(new Double(cell.getNumericCellValue()).intValue());
    } else if (type.equals(Boolean.class.getName())) {
        return ExcelUtil.getBoolean(cell,
                (MdAttributeBooleanDAOIF) this.getMdAttribute().getMdAttributeConcrete());
    } else if (type.equals(java.util.Date.class.getName())) {
        return cell.getDateCellValue();
    }
    String error = "The type [" + type + "] is not supported as a parameter.";
    throw new ProgrammingErrorException(error);
}

From source file:com.runwaysdk.dataaccess.io.excel.DateFieldColumn.java

License:Open Source License

public Object getCellValue(Cell cell) throws Exception {
    return cell.getDateCellValue();
}

From source file:com.siacra.beans.GrupoBean.java

public void archivoXlsx(String path, FileUploadEvent archivo) {
    excelResponse = new ArrayList<>();
    List<Horario> horas = new ArrayList<>();

    try {/*from w  w  w .ja va2  s  . com*/
        FileInputStream file = new FileInputStream(new File(path + "\\" + archivo.getFile().getFileName()));

        // Crear el objeto que tendra el libro de Excel
        XSSFWorkbook workbook = new XSSFWorkbook(file);

        /*
         * Obtenemos la primera pestaa a la que se quiera procesar indicando el indice.
         * Una vez obtenida la hoja excel con las filas que se quieren leer obtenemos el iterator
         * que nos permite recorrer cada una de las filas que contiene.
        */

        XSSFSheet sheet = workbook.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.iterator();
        Row row;

        // Recorremos todas las filas para mostrar el contenido de cada celda

        int cantidad = 0;
        int cantidad2 = 0;

        while (rowIterator.hasNext()) {
            row = rowIterator.next();

            if (cantidad2 != 0) {
                Horario h = new Horario();
                UpploadGrupos grupo = new UpploadGrupos();
                // Obtenemos el iterator que permite recorres todas las celdas de una fila
                Iterator<Cell> cellIterator = row.cellIterator();
                Cell celda;

                cantidad = 1;

                while (cellIterator.hasNext()) {
                    celda = cellIterator.next();

                    //                        if((cantidad%10)==0)
                    //                        {
                    //                            System.out.print(grupo.toString());
                    //                            excelResponse.add(grupo);
                    //                            grupo = new UpploadGrupos();
                    //                            cantidad=1;
                    //                        }

                    // Dependiendo del formato de la celda el valor se debe mostrar como String, Fecha, boolean, entero...
                    switch (celda.getCellType()) {
                    case Cell.CELL_TYPE_NUMERIC:
                        if (DateUtil.isCellDateFormatted(celda)) {

                            SimpleDateFormat f = new SimpleDateFormat("HH:mm:ss");
                            String fecha = f.format(celda.getDateCellValue());
                            System.out.print(":::::::: " + fecha);
                            Date dos = f.parse(fecha);

                            if (cantidad == 4) {
                                h.setHinicio1(dos);
                                grupo.setInicio1(dos);
                                cantidad++;
                            } else if (cantidad == 5) {
                                h.setHfin1(dos);
                                grupo.setFin1(dos);
                                cantidad++;
                            } else if (cantidad == 7) {
                                h.setHinicio2(dos);
                                grupo.setInicio2(dos);
                                cantidad++;
                            } else if (cantidad == 8) {
                                h.setHfin2(dos);
                                grupo.setFin2(dos);
                                cantidad++;
                            }

                            System.out.println(dos);
                        }
                        //                                else
                        //                                {
                        //                                   double numero = celda.getNumericCellValue();
                        //                                   System.out.println(celda.getNumericCellValue());
                        //                                }
                        break;

                    case Cell.CELL_TYPE_STRING:
                        if (cantidad == 1) {
                            grupo.setAsignatura(celda.getStringCellValue());
                            cantidad++;
                        } else if (cantidad == 2) {
                            grupo.setTipoGrupo(celda.getStringCellValue());
                            cantidad++;
                        } else if (cantidad == 3) {
                            h.setDia1(celda.getStringCellValue());
                            grupo.setDia1(celda.getStringCellValue());
                            cantidad++;
                        } else if (cantidad == 6) {
                            h.setDia2(celda.getStringCellValue());
                            grupo.setDia2(celda.getStringCellValue());
                            cantidad++;
                        } else if (cantidad == 9) {
                            grupo.setNumeroGrupo(celda.getStringCellValue());
                            cantidad++;
                        } else if (cantidad == 10) {
                            grupo.setCupos(celda.getStringCellValue());
                            cantidad++;
                        }
                        String texto = celda.getStringCellValue();
                        System.out.println(celda.getStringCellValue());
                        break;

                    //                        case Cell.CELL_TYPE_BOOLEAN:
                    //                            System.out.println(celda.getBooleanCellValue());
                    //                            break;

                    }//fin if que obtiene valor de celda
                } //fin while que recorre celdas
                System.out.print("objeto:::" + grupo.toString());
                System.out.print("objeto:::" + h.toString());
                horas.add(h);
                excelResponse.add(grupo);
            } // fin if primera iteracion

            cantidad2++;
        } // fin while que recorre filas
          // cerramos el libro excel
        workbook.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    procesarListaCargada();

}

From source file:com.siberhus.tdfl.excel.DefaultExcelRowReader.java

License:Apache License

private Object getCellValue(Cell cell) {
    if (cell == null)
        return null;
    switch (cell.getCellType()) {
    case Cell.CELL_TYPE_STRING:
        RichTextString rts = cell.getRichStringCellValue();
        if (rts != null) {
            return rts.getString();
        }//  w  w w  .j a v  a2  s.co  m
        return null;
    case Cell.CELL_TYPE_NUMERIC:
        String value = cell.toString();
        /*
         * In POI we cannot know which cell is date or number because both
         * cells have numeric type To fix this problem we need to call
         * toString if it's number cell we can parse it but if it's date
         * cell we cannot parse the value with number parser
         */
        try {
            return new BigDecimal(value);
        } catch (Exception e) {
            return cell.getDateCellValue();
        }
    case Cell.CELL_TYPE_BLANK:
        return null;
    case Cell.CELL_TYPE_BOOLEAN:
        return cell.getBooleanCellValue();
    case Cell.CELL_TYPE_FORMULA:
        return cell.getCellFormula();
    }
    return null;
}

From source file:com.streamsets.pipeline.lib.parser.excel.Cells.java

License:Apache License

static Field parseCell(Cell cell, FormulaEvaluator evaluator) throws ExcelUnsupportedCellTypeException {
    CellType cellType = cell.getCellTypeEnum();
    // set the cellType of a formula cell to its cached formula result type in order to process it as its result type
    boolean isFormula = cell.getCellTypeEnum().equals(CellType.FORMULA);
    if (isFormula) {
        cellType = cell.getCachedFormulaResultTypeEnum();
    }/*from  ww  w. java  2s . c om*/

    switch (cellType) {
    case STRING:
        return Field.create(cell.getStringCellValue());
    case NUMERIC:
        Double rawValue = cell.getNumericCellValue(); // resolves formulas automatically and gets value without cell formatting
        String displayValue = isFormula ? evaluator.evaluate(cell).formatAsString()
                : dataFormatter.formatCellValue(cell);
        boolean numericallyEquivalent = false;
        try {
            numericallyEquivalent = Double.parseDouble(displayValue) == rawValue;
        } catch (NumberFormatException e) {
        }

        if (DateUtil.isCellDateFormatted(cell)) {
            // It's a date, not a number
            java.util.Date dt = cell.getDateCellValue();
            // if raw number is < 1 then it's a time component only, otherwise date.
            return rawValue < 1 ? Field.createTime(dt) : Field.createDate(dt);
        }

        // some machinations to handle integer values going in without decimal vs. with .0 for rawValue
        return Field
                .create(numericallyEquivalent ? new BigDecimal(displayValue) : BigDecimal.valueOf(rawValue));

    case BOOLEAN:
        return Field.create(cell.getBooleanCellValue());
    case BLANK:
        return Field.create("");
    default:
        throw new ExcelUnsupportedCellTypeException(cell, cellType);
    }
}

From source file:com.tecacet.jflat.excel.PoiExcelReader.java

License:Apache License

private String getCellContentAsString(Cell cell) {
    switch (cell.getCellType()) {
    case Cell.CELL_TYPE_STRING:
        return cell.getRichStringCellValue().getString();
    case Cell.CELL_TYPE_NUMERIC:
        if (DateUtil.isCellDateFormatted(cell)) {
            return cell.getDateCellValue().toString();
        } else {/*w  w  w .  java  2 s. c om*/
            double d = cell.getNumericCellValue();
            // TODO find a flexible enough format for all numeric types
            return numberFormat.format(d);
            // return Double.toString(d);
        }
    case Cell.CELL_TYPE_BOOLEAN:
        boolean b = cell.getBooleanCellValue();
        return Boolean.toString(b);
    case Cell.CELL_TYPE_FORMULA:
        return cell.getCellFormula();
    case Cell.CELL_TYPE_BLANK:
        return "";
    case Cell.CELL_TYPE_ERROR:
        byte bt = cell.getErrorCellValue();
        return Byte.toString(bt);
    default:
        return cell.getStringCellValue();

    }
}

From source file:com.vaadin.addon.spreadsheet.CellValueManager.java

License:Open Source License

public String getOriginalCellValue(Cell cell) {
    if (cell == null) {
        return "";
    }/* w  w  w.  j  ava  2  s .  c  o m*/

    int cellType = cell.getCellType();
    switch (cellType) {
    case Cell.CELL_TYPE_FORMULA:
        return cell.getCellFormula();
    case Cell.CELL_TYPE_NUMERIC:
        if (DateUtil.isCellDateFormatted(cell)) {
            Date dateCellValue = cell.getDateCellValue();
            if (dateCellValue != null) {
                return new SimpleDateFormat().format(dateCellValue);
            }
            return "";
        }
        return originalValueDecimalFormat.format(cell.getNumericCellValue());
    case Cell.CELL_TYPE_STRING:
        return cell.getStringCellValue();
    case Cell.CELL_TYPE_BOOLEAN:
        return String.valueOf(cell.getBooleanCellValue());
    case Cell.CELL_TYPE_BLANK:
        return "";
    case Cell.CELL_TYPE_ERROR:
        return String.valueOf(cell.getErrorCellValue());
    }
    return "";
}