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:org.datanucleus.store.excel.ExcelPersistenceHandler.java

License:Open Source License

/**
 * Fetches fields of a persistent object from the database.
 * @param op The ObjectProvider of the object to be fetched.
 * @param fieldNumbers The numbers of the fields to be fetched.
 * @throws NucleusDataStoreException when an error occurs in the datastore communication
 */// w  w  w.  j a va  2s  .com
public void fetchObject(final ObjectProvider op, int[] fieldNumbers) {
    AbstractClassMetaData cmd = op.getClassMetaData();
    if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
        // Debug information about what we are retrieving
        StringBuilder str = new StringBuilder("Fetching object \"");
        str.append(op.getObjectAsPrintable()).append("\" (id=");
        str.append(op.getInternalObjectId()).append(")").append(" fields [");
        for (int i = 0; i < fieldNumbers.length; i++) {
            if (i > 0) {
                str.append(",");
            }
            str.append(cmd.getMetaDataForManagedMemberAtAbsolutePosition(fieldNumbers[i]).getName());
        }
        str.append("]");
        NucleusLogger.PERSISTENCE.debug(str.toString());
    }

    ExecutionContext ec = op.getExecutionContext();
    ManagedConnection mconn = storeMgr.getConnection(ec);
    try {
        Workbook wb = (Workbook) mconn.getConnection();
        if (!storeMgr.managesClass(cmd.getFullClassName())) {
            // Make sure schema exists, using this connection
            ((ExcelStoreManager) storeMgr).manageClasses(new String[] { cmd.getFullClassName() },
                    ec.getClassLoaderResolver(), wb);
        }
        Table table = ec.getStoreManager().getStoreDataForClass(cmd.getFullClassName()).getTable();
        final Sheet sheet = ExcelUtils.getSheetForClass(op, wb, table);

        long startTime = System.currentTimeMillis();
        if (NucleusLogger.DATASTORE_RETRIEVE.isDebugEnabled()) {
            NucleusLogger.DATASTORE_RETRIEVE.debug(
                    Localiser.msg("Excel.Fetch.Start", op.getObjectAsPrintable(), op.getInternalObjectId()));
        }

        int rowNumber = ExcelUtils.getRowNumberForObjectInWorkbook(op, wb, false, table);
        if (rowNumber < 0) {
            throw new NucleusObjectNotFoundException("object not found", op.getObject());
        }
        op.replaceFields(fieldNumbers, new FetchFieldManager(op, sheet, rowNumber, table));

        if (NucleusLogger.DATASTORE_RETRIEVE.isDebugEnabled()) {
            NucleusLogger.DATASTORE_RETRIEVE
                    .debug(Localiser.msg("Excel.ExecutionTime", (System.currentTimeMillis() - startTime)));
        }
        if (ec.getStatistics() != null) {
            ec.getStatistics().incrementNumReads();
            ec.getStatistics().incrementFetchCount();
        }

        VersionMetaData vermd = cmd.getVersionMetaDataForClass();
        if (vermd != null && op.getTransactionalVersion() == null) {
            // Object has no version set so update it from this fetch
            long verColNo = -1;
            if (vermd.getFieldName() == null) {
                // Surrogate version
                verColNo = table.getVersionColumn().getPosition();
            } else {
                // Field-based version
                verColNo = table.getMemberColumnMappingForMember(cmd.getMetaDataForMember(vermd.getFieldName()))
                        .getColumn(0).getPosition();
            }

            Row row = sheet.getRow(rowNumber);
            Cell cell = row.getCell((int) verColNo);
            if (vermd.getVersionStrategy() == VersionStrategy.VERSION_NUMBER) {
                op.setVersion(Long.valueOf((long) cell.getNumericCellValue()));
            } else if (vermd.getVersionStrategy() == VersionStrategy.DATE_TIME) {
                op.setVersion(cell.getDateCellValue());
            }
        }
    } finally {
        mconn.release();
    }
}

From source file:org.datanucleus.store.excel.ExcelUtils.java

License:Open Source License

/**
 * Convenience method to check if a cell value matches the provided value and type.
 * @param cell The cell// w  w  w  .  ja v a  2 s.c  o m
 * @param fieldType The type to compare it with
 * @param fieldValue The value of the type to compare it with (can be null)
 * @return Whether the cell matches
 */
protected static boolean cellMatches(Cell cell, Class fieldType, Object fieldValue) {
    if (cell == null) {
        return false;
    }

    if (String.class.isAssignableFrom(fieldType)
            && cell.getRichStringCellValue().getString().equals(fieldValue)) {
        return true;
    } else if ((fieldType == int.class || fieldType == Integer.class)
            && ((Integer) fieldValue).intValue() == (int) cell.getNumericCellValue()) {
        return true;
    } else if ((fieldType == long.class || fieldType == Long.class)
            && ((Long) fieldValue).longValue() == (long) cell.getNumericCellValue()) {
        return true;
    } else if ((fieldType == short.class || fieldType == Short.class)
            && ((Short) fieldValue).shortValue() == (short) cell.getNumericCellValue()) {
        return true;
    } else if ((fieldType == float.class || fieldType == Float.class)
            && ((Float) fieldValue).floatValue() == (float) cell.getNumericCellValue()) {
        return true;
    } else if ((fieldType == double.class || fieldType == Double.class)
            && ((Double) fieldValue).doubleValue() == cell.getNumericCellValue()) {
        return true;
    } else if ((fieldType == boolean.class || fieldType == Boolean.class)
            && ((Boolean) fieldValue).booleanValue() == cell.getBooleanCellValue()) {
        return true;
    } else if ((fieldType == byte.class || fieldType == Byte.class)
            && ((Byte) fieldValue).byteValue() == (byte) cell.getNumericCellValue()) {
        return true;
    } else if ((fieldType == char.class || fieldType == Character.class)
            && ((Character) fieldValue).charValue() == cell.getRichStringCellValue().getString().charAt(0)) {
        return true;
    } else if ((Date.class.isAssignableFrom(fieldType)
            && ((Date) fieldValue).getTime() == cell.getDateCellValue().getTime())) {
        return true;
    }
    return false;
}

From source file:org.datanucleus.store.excel.fieldmanager.FetchFieldManager.java

License:Open Source License

protected Object fetchObjectFieldInternal(int fieldNumber, AbstractMemberMetaData mmd, ClassLoaderResolver clr,
        RelationType relationType) {
    MemberColumnMapping mapping = getColumnMapping(fieldNumber);

    if (relationType == RelationType.NONE) {
        Column col = mapping.getColumn(0);
        if (mapping.getTypeConverter() != null) {
            TypeConverter conv = mapping.getTypeConverter();
            if (mapping.getNumberOfColumns() == 1) {
                Cell cell = sheet.getRow(rowNumber)
                        .getCell(getColumnMapping(fieldNumber).getColumn(0).getPosition());
                if (cell == null) {
                    return null;
                }//from   w  ww.  ja va 2s .  c  o m

                Object value = null;
                Class datastoreType = TypeConverterHelper.getDatastoreTypeForTypeConverter(conv, mmd.getType());
                if (datastoreType == String.class) {
                    value = conv.toMemberType(cell.getRichStringCellValue().getString());
                } else if (Number.class.isAssignableFrom(datastoreType)) {
                    value = conv.toMemberType(cell.getNumericCellValue());
                } else if (Boolean.class.isAssignableFrom(datastoreType)) {
                    value = conv.toMemberType(cell.getBooleanCellValue());
                } else if (Date.class.isAssignableFrom(datastoreType)) {
                    value = conv.toMemberType(cell.getDateCellValue());
                } else {
                    NucleusLogger.DATASTORE_PERSIST.warn("TypeConverter for member " + mmd.getFullFieldName()
                            + " converts to " + datastoreType.getName() + " - not yet supported");
                }

                if (op != null) {
                    return SCOUtils.wrapSCOField(op, fieldNumber, value, true);
                }
                return value;
            }

            // Member stored in multiple columns and convertable using TypeConverter
            boolean isNull = true;
            Object valuesArr = null;
            Class[] colTypes = ((MultiColumnConverter) conv).getDatastoreColumnTypes();
            if (colTypes[0] == int.class) {
                valuesArr = new int[mapping.getNumberOfColumns()];
            } else if (colTypes[0] == long.class) {
                valuesArr = new long[mapping.getNumberOfColumns()];
            } else if (colTypes[0] == double.class) {
                valuesArr = new double[mapping.getNumberOfColumns()];
            } else if (colTypes[0] == float.class) {
                valuesArr = new double[mapping.getNumberOfColumns()];
            } else if (colTypes[0] == String.class) {
                valuesArr = new String[mapping.getNumberOfColumns()];
            }
            // TODO Support other types
            else {
                valuesArr = new Object[mapping.getNumberOfColumns()];
            }

            for (int i = 0; i < mapping.getNumberOfColumns(); i++) {
                Cell cell = sheet.getRow(rowNumber).getCell(mapping.getColumn(i).getPosition());
                if (cell == null) {
                    Array.set(valuesArr, i, null);
                } else {
                    isNull = false;
                    if (colTypes[i] == int.class) {
                        Object cellValue = getValueFromCellOfType(cell, Integer.class,
                                mapping.getColumn(i).getJdbcType());
                        Array.set(valuesArr, i, ((Integer) cellValue).intValue());
                    } else if (colTypes[i] == long.class) {
                        Object cellValue = getValueFromCellOfType(cell, Long.class,
                                mapping.getColumn(i).getJdbcType());
                        Array.set(valuesArr, i, ((Long) cellValue).longValue());
                    } else {
                        Object cellValue = getValueFromCellOfType(cell, colTypes[i],
                                mapping.getColumn(i).getJdbcType());
                        Array.set(valuesArr, i, cellValue);
                    }
                }
            }

            if (isNull) {
                return null;
            }

            Object memberValue = conv.toMemberType(valuesArr);
            if (op != null && memberValue != null) {
                memberValue = SCOUtils.wrapSCOField(op, fieldNumber, memberValue, true);
            }
            return memberValue;
        }

        Cell cell = sheet.getRow(rowNumber).getCell(mapping.getColumn(0).getPosition());
        if (cell == null) {
            return null;
        }

        Object value = getValueFromCellOfType(cell, mmd.getType(), col.getJdbcType());

        // Wrap the field if it is SCO
        if (op != null) {
            return SCOUtils.wrapSCOField(op, fieldNumber, value, true);
        }
        return value;
    } else if (RelationType.isRelationSingleValued(relationType)) {
        // Persistable object stored as String reference of the identity
        Cell cell = sheet.getRow(rowNumber).getCell(mapping.getColumn(0).getPosition());
        if (cell == null) {
            return null;
        }

        String idStr = cell.getRichStringCellValue().getString();
        if (idStr == null) {
            return null;
        }

        if (idStr.startsWith("[") && idStr.endsWith("]")) {
            idStr = idStr.substring(1, idStr.length() - 1);
            Object obj = null;
            AbstractClassMetaData memberCmd = ec.getMetaDataManager().getMetaDataForClass(mmd.getType(), clr);
            try {
                if (memberCmd.usesSingleFieldIdentityClass() && idStr.indexOf(':') > 0) {
                    // Uses persistent identity
                    obj = IdentityUtils.getObjectFromPersistableIdentity(idStr, memberCmd, ec);
                } else {
                    // Uses legacy identity
                    obj = IdentityUtils.getObjectFromIdString(idStr, memberCmd, ec, true);
                }
            } catch (NucleusObjectNotFoundException nfe) {
                NucleusLogger.GENERAL.warn("Object=" + op + " field=" + mmd.getFullFieldName() + " has id="
                        + idStr + " but could not instantiate object with that identity");
                return null;
            }
            return obj;
        }

        return null;
    } else if (RelationType.isRelationMultiValued(relationType)) {
        // Collection/Map/Array
        Cell cell = sheet.getRow(rowNumber).getCell(mapping.getColumn(0).getPosition());
        if (cell == null) {
            return null;
        }

        String cellStr = cell.getRichStringCellValue().getString();
        if (cellStr == null) {
            return null;
        }

        if (cellStr.startsWith("[") && cellStr.endsWith("]")) {
            cellStr = cellStr.substring(1, cellStr.length() - 1);
            String[] components = MetaDataUtils.getInstance().getValuesForCommaSeparatedAttribute(cellStr);
            if (Collection.class.isAssignableFrom(mmd.getType())) {
                Collection<Object> coll;
                try {
                    Class instanceType = SCOUtils.getContainerInstanceType(mmd.getType(),
                            mmd.getOrderMetaData() != null);
                    coll = (Collection<Object>) instanceType.newInstance();
                } catch (Exception e) {
                    throw new NucleusDataStoreException(e.getMessage(), e);
                }

                boolean changeDetected = false;
                if (components != null) {
                    AbstractClassMetaData elementCmd = mmd.getCollection()
                            .getElementClassMetaData(ec.getClassLoaderResolver(), ec.getMetaDataManager());
                    for (int i = 0; i < components.length; i++) {
                        // TODO handle Collection<interface>
                        Object element = null;
                        try {
                            if (elementCmd.usesSingleFieldIdentityClass() && components[i].indexOf(':') > 0) {
                                // Uses persistent identity
                                element = IdentityUtils.getObjectFromPersistableIdentity(components[i],
                                        elementCmd, ec);
                            } else {
                                // Uses legacy identity
                                element = IdentityUtils.getObjectFromIdString(components[i], elementCmd, ec,
                                        true);
                            }
                            coll.add(element);
                        } catch (NucleusObjectNotFoundException nfe) {
                            // Object no longer exists. Deleted by user? so ignore
                            changeDetected = true;
                        }
                    }
                }
                if (op != null) {
                    coll = (Collection) SCOUtils.wrapSCOField(op, fieldNumber, coll, true);
                    if (changeDetected) {
                        op.makeDirty(mmd.getAbsoluteFieldNumber());
                    }
                }
                return coll;
            } else if (Map.class.isAssignableFrom(mmd.getType())) {
                AbstractClassMetaData keyCmd = mmd.getMap().getKeyClassMetaData(clr, ec.getMetaDataManager());
                AbstractClassMetaData valCmd = mmd.getMap().getValueClassMetaData(clr, ec.getMetaDataManager());

                Map map;
                try {
                    Class instanceType = SCOUtils.getContainerInstanceType(mmd.getType(), false);
                    map = (Map) instanceType.newInstance();
                } catch (Exception e) {
                    throw new NucleusDataStoreException(e.getMessage(), e);
                }

                boolean changeDetected = false;
                if (components != null) {
                    for (int i = 0; i < components.length; i++) {
                        String keyCmpt = components[i];
                        i++;
                        String valCmpt = components[i];

                        // Strip square brackets from entry bounds
                        String keyStr = keyCmpt.substring(1, keyCmpt.length() - 1);
                        String valStr = valCmpt.substring(1, valCmpt.length() - 1);

                        boolean keySet = true;
                        boolean valSet = true;
                        Object key = null;
                        if (keyCmd != null) {
                            try {
                                // TODO handle Map<interface, ?>
                                if (keyCmd.usesSingleFieldIdentityClass() && keyStr.indexOf(':') > 0) {
                                    // Uses persistent identity
                                    key = IdentityUtils.getObjectFromPersistableIdentity(keyStr, keyCmd, ec);
                                } else {
                                    // Uses legacy identity
                                    key = IdentityUtils.getObjectFromIdString(keyStr, keyCmd, ec, true);
                                }
                            } catch (NucleusObjectNotFoundException nfe) {
                                // Object no longer exists. Deleted by user? so ignore
                                changeDetected = true;
                                keySet = false;
                            }
                        } else {
                            String keyTypeName = mmd.getMap().getKeyType();
                            Class keyType = ec.getClassLoaderResolver().classForName(keyTypeName);
                            if (Enum.class.isAssignableFrom(keyType)) {
                                key = Enum.valueOf(keyType, keyStr);
                            } else if (keyType == String.class) {
                                key = keyStr;
                            } else {
                                // TODO Support other map key types
                                throw new NucleusException(
                                        "Don't currently support retrieval of Maps with keys of type "
                                                + keyTypeName + " (field=" + mmd.getFullFieldName() + ")");
                            }
                        }

                        Object val = null;
                        if (valCmd != null) {
                            try {
                                // TODO handle Collection<?, interface>
                                if (valCmd.usesSingleFieldIdentityClass() && valStr.indexOf(':') > 0) {
                                    // Uses persistent identity
                                    val = IdentityUtils.getObjectFromPersistableIdentity(valStr, valCmd, ec);
                                } else {
                                    // Uses legacy identity
                                    val = IdentityUtils.getObjectFromIdString(valStr, valCmd, ec, true);
                                }
                            } catch (NucleusObjectNotFoundException nfe) {
                                // Object no longer exists. Deleted by user? so ignore
                                changeDetected = true;
                                valSet = false;
                            }
                        } else {
                            String valTypeName = mmd.getMap().getValueType();
                            Class valType = ec.getClassLoaderResolver().classForName(valTypeName);
                            if (Enum.class.isAssignableFrom(valType)) {
                                val = Enum.valueOf(valType, valStr);
                            } else if (valType == String.class) {
                                val = valStr;
                            } else {
                                // TODO Support other map value types
                                throw new NucleusException(
                                        "Don't currently support retrieval of Maps with values of type "
                                                + valTypeName + " (field=" + mmd.getFullFieldName() + ")");
                            }
                        }

                        if (keySet && valSet) {
                            map.put(key, val);
                        }
                    }
                }
                if (op != null) {
                    map = (Map) SCOUtils.wrapSCOField(op, fieldNumber, map, true);
                    if (changeDetected) {
                        op.makeDirty(mmd.getAbsoluteFieldNumber());
                    }
                }
                return map;
            } else if (mmd.getType().isArray()) {
                Object array = null;
                boolean changeDetected = false;
                int pos = 0;
                if (components != null) {
                    AbstractClassMetaData elementCmd = mmd.getCollection()
                            .getElementClassMetaData(ec.getClassLoaderResolver(), ec.getMetaDataManager());
                    array = Array.newInstance(mmd.getType().getComponentType(), components.length);
                    for (int i = 0; i < components.length; i++) {
                        // TODO handle interface[]
                        Object element = null;
                        try {
                            if (elementCmd.usesSingleFieldIdentityClass() && components[i].indexOf(':') > 0) {
                                // Uses persistent identity
                                element = IdentityUtils.getObjectFromPersistableIdentity(components[i],
                                        elementCmd, ec);
                            } else {
                                // Uses legacy identity
                                element = IdentityUtils.getObjectFromIdString(components[i], elementCmd, ec,
                                        true);
                            }
                            Array.set(array, pos++, element);
                        } catch (NucleusObjectNotFoundException nfe) {
                            // Object no longer exists. Deleted by user? so ignore
                            changeDetected = true;
                        }
                    }
                } else {
                    array = Array.newInstance(mmd.getType().getComponentType(), 0);
                }

                if (changeDetected) {
                    if (pos < Array.getLength(array)) {
                        // Some elements not found, so resize the array
                        Object arrayOld = array;
                        array = Array.newInstance(mmd.getType().getComponentType(), pos);
                        for (int j = 0; j < pos; j++) {
                            Array.set(array, j, Array.get(arrayOld, j));
                        }
                    }
                    if (op != null) {
                        array = SCOUtils.wrapSCOField(op, fieldNumber, array, true);
                        if (changeDetected) {
                            op.makeDirty(mmd.getAbsoluteFieldNumber());
                        }
                    }
                }
                return array;
            }
        }
    }
    throw new NucleusException("Dont currently support retrieval of type " + mmd.getTypeName());
}

From source file:org.datanucleus.store.excel.fieldmanager.FetchFieldManager.java

License:Open Source License

protected Object getValueFromCellOfType(Cell cell, Class requiredType, JdbcType jdbcType) {
    if (Date.class.isAssignableFrom(requiredType)) {
        Date date = cell.getDateCellValue();
        if (date == null) {
            return null;
        }/*from   w ww .  j a  va2 s  .com*/

        Object value = date;
        if (requiredType == java.sql.Date.class) {
            value = new java.sql.Date(date.getTime());
        } else if (requiredType == java.sql.Time.class) {
            value = new java.sql.Time(date.getTime());
        } else if (requiredType == java.sql.Timestamp.class) {
            value = new java.sql.Timestamp(date.getTime());
        }
        return value;
    } else if (Calendar.class.isAssignableFrom(requiredType)) {
        Date date = cell.getDateCellValue();
        if (date == null) {
            return null;
        }

        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal;
    } else if (Boolean.class.isAssignableFrom(requiredType)) {
        boolean boolValue = cell.getBooleanCellValue();
        return Boolean.valueOf(boolValue);
    } else if (Character.class.isAssignableFrom(requiredType)) {
        String strValue = cell.getRichStringCellValue().getString();
        return Character.valueOf(strValue.charAt(0));
    } else if (Number.class.isAssignableFrom(requiredType)) {
        double val = cell.getNumericCellValue();
        if (Double.class.isAssignableFrom(requiredType)) {
            return Double.valueOf(val);
        } else if (Float.class.isAssignableFrom(requiredType)) {
            return Float.valueOf((float) val);
        } else if (Integer.class.isAssignableFrom(requiredType)) {
            return Integer.valueOf((int) val);
        } else if (Long.class.isAssignableFrom(requiredType)) {
            return Long.valueOf((long) val);
        } else if (Short.class.isAssignableFrom(requiredType)) {
            return Short.valueOf((short) val);
        } else if (Byte.class.isAssignableFrom(requiredType)) {
            return Byte.valueOf((byte) val);
        } else if (BigDecimal.class.isAssignableFrom(requiredType)) {
            return new BigDecimal(val);
        } else if (BigInteger.class.isAssignableFrom(requiredType)) {
            return new BigInteger("" + val);
        }
    } else if (Enum.class.isAssignableFrom(requiredType)) {
        if (MetaDataUtils.isJdbcTypeNumeric(jdbcType)) {
            double value = cell.getNumericCellValue();
            return requiredType.getEnumConstants()[(int) value];
        }

        String value = cell.getRichStringCellValue().getString();
        if (value != null && value.length() > 0) {
            return Enum.valueOf(requiredType, value);
        }

        return null;
    } else if (requiredType == byte[].class) {
        String value = cell.getStringCellValue();
        if (value != null) {
            return Base64.decode(value);
        }
    }

    // Fallback to String/Long TypeConverters
    if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
        TypeConverter longConv = ec.getNucleusContext().getTypeManager().getTypeConverterForType(requiredType,
                Long.class);
        return longConv.toMemberType((long) cell.getNumericCellValue());
    } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
        TypeConverter strConv = ec.getNucleusContext().getTypeManager().getTypeConverterForType(requiredType,
                String.class);
        String cellValue = (cell.getRichStringCellValue() != null ? cell.getRichStringCellValue().getString()
                : null);
        if (cellValue != null && cellValue.length() > 0) {
            return strConv.toMemberType(cell.getRichStringCellValue().getString());
        }
    }

    // Not supported as String so just set to null
    NucleusLogger.PERSISTENCE.warn("Field could not be set in the object since it is not persistable to Excel");
    return null;
}

From source file:org.dbflute.helper.io.xls.DfTableXlsReader.java

License:Apache License

protected Object extractCellValue(DfDataTable table, int columnIndex, Row row, Cell cell) {
    if (cell == null) {
        return isEmptyStringTarget(table, columnIndex) ? "" : null;
    }/*from  www  . j  a va2 s  .c  o m*/
    switch (cell.getCellType()) {
    case Cell.CELL_TYPE_NUMERIC:
        if (isCellDateFormatted(cell)) {
            return DfTypeUtil.toTimestamp(cell.getDateCellValue());
        }
        final double numericCellValue = cell.getNumericCellValue();
        if (isInt(numericCellValue)) {
            return new BigDecimal((int) numericCellValue);
        }
        return new BigDecimal(Double.toString(numericCellValue));
    case Cell.CELL_TYPE_STRING:
        return processRichStringCellValue(table, columnIndex, row, cell);
    case Cell.CELL_TYPE_BOOLEAN:
        boolean b = cell.getBooleanCellValue();
        return Boolean.valueOf(b);
    default:
        return isEmptyStringTarget(table, columnIndex) ? "" : null;
    }
}

From source file:org.diffkit.diff.sns.DKPoiSheet.java

License:Apache License

private static Object readCell(Cell cell_, Type type_) {
    if (IS_DEBUG_ENABLED) {
        LOG.debug("cell_->{}", cell_ == null ? null : cell_);
        LOG.debug("type_->{}", type_);
    }/*w ww.  java  2 s  .c  o  m*/
    if ((cell_ == null) || (type_ == null))
        return null;
    try {
        if (cell_.getCellType() == Cell.CELL_TYPE_BLANK)
            return null;
        switch (type_) {
        case STRING:
            return cell_.toString();
        case DATE:
            return cell_.getDateCellValue();
        case DECIMAL:
            return new BigDecimal(cell_.toString());
        case INTEGER:
            return new Long(new Double(cell_.getNumericCellValue()).longValue());
        case REAL:
            return new Double(cell_.getNumericCellValue());
        case BOOLEAN:
            return Boolean.valueOf(cell_.getBooleanCellValue());
        case TIME:
            return readTime(cell_);
        case TIMESTAMP:
            return readTimestamp(cell_);
        case MIXED:
            return cell_.toString();
        default:
            return cell_.toString();
        }
    } catch (Exception e_) {
        String message = String.format("unable to read cell_->%s type_->%s", cell_, type_);
        throw new RuntimeException(message, e_);
    }
}

From source file:org.diffkit.diff.sns.DKPoiSheet.java

License:Apache License

private static Time readTime(Cell cell_) {
    Date dateValue = cell_.getDateCellValue();
    if (dateValue == null)
        return null;
    return new Time(dateValue.getTime());
}

From source file:org.diffkit.diff.sns.DKPoiSheet.java

License:Apache License

private static Timestamp readTimestamp(Cell cell_) {
    Date dateValue = cell_.getDateCellValue();
    if (dateValue == null)
        return null;
    return new Timestamp(dateValue.getTime());
}

From source file:org.displaytag.export.excel.SubtotaledExcelTest.java

License:Open Source License

/**
 * Test no groups.//from  www.  ja  va 2  s.  c  o m
 *
 * @throws Exception the exception
 */
@Test
public void testNoGroups() throws Exception {
    TableModel m = getModel();
    for (HeaderCell cell : m.getHeaderCellList()) {
        cell.setGroup(0);
    }
    TableTotaler tt = new TableTotaler();
    m.setTotaler(tt);
    HssfDoubleExportView view = new HssfDoubleExportView();
    tt.init(m);
    view.setParameters(m, true, true, true);

    File f = File.createTempFile("nogroups", null);
    FileOutputStream str = new FileOutputStream(f);
    view.doExport(str);
    str.flush();
    str.close();

    FileInputStream istr = new FileInputStream(f);
    Workbook wb = new HSSFWorkbook(istr);

    Sheet sh = wb.getSheetAt(0);

    Cell a2 = sh.getRow(1).getCell(0);
    Cell b2 = sh.getRow(1).getCell(1);
    Cell d2 = sh.getRow(1).getCell(3);
    Cell e2 = sh.getRow(1).getCell(4);
    assertEquals("ant", a2.getStringCellValue());
    assertEquals("bee", b2.getStringCellValue());
    assertEquals(KnownValue.MAY, e2.getDateCellValue());
    assertEquals(2, (int) d2.getNumericCellValue());

}

From source file:org.drools.scorecards.parser.xls.XLSScorecardParser.java

License:Apache License

private void processSheet(HSSFSheet worksheet) throws ScorecardParseException {
    for (Row row : worksheet) {
        int currentRowCtr = row.getRowNum();
        excelDataCollector.newRow(currentRowCtr);
        for (Cell cell : row) {
            int currentColCtr = cell.getColumnIndex();
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                excelDataCollector.newCell(currentRowCtr, currentColCtr, cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    excelDataCollector.newCell(currentRowCtr, currentColCtr, cell.getDateCellValue());
                } else {
                    excelDataCollector.newCell(currentRowCtr, currentColCtr,
                            Double.valueOf(cell.getNumericCellValue()));
                }//ww w.j  av  a  2s .c o m
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                excelDataCollector.newCell(currentRowCtr, currentColCtr,
                        Boolean.valueOf(cell.getBooleanCellValue()).toString());
                break;
            case Cell.CELL_TYPE_FORMULA:
                break;
            case Cell.CELL_TYPE_BLANK:
                excelDataCollector.newCell(currentRowCtr, currentColCtr, "");
                break;
            }
        }
    }
}