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

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

Introduction

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

Prototype

double getNumericCellValue();

Source Link

Document

Get the value of the cell as a number.

Usage

From source file:de.jlo.talendcomp.excel.SpreadsheetReferencedCellInput.java

License:Apache License

private String getStringCellValue(Cell cell) {
    String value = null;/*ww w .ja  v a2 s.  c om*/
    if (cell != null) {
        CellType cellType = cell.getCellTypeEnum();
        if (cellType == CellType.FORMULA) {
            value = getDataFormatter().formatCellValue(cell, getFormulaEvaluator());
        } else if (cellType == CellType.STRING) {
            if (returnURLInsteadOfName) {
                Hyperlink link = cell.getHyperlink();
                if (link != null) {
                    if (concatenateLabelUrl) {
                        String url = link.getAddress();
                        if (url == null) {
                            url = "";
                        }
                        String label = link.getLabel();
                        if (label == null) {
                            label = "";
                        }
                        value = label + "|" + url;
                    } else {
                        value = link.getAddress();
                    }
                } else {
                    value = cell.getStringCellValue();
                }
            } else {
                value = cell.getStringCellValue();
            }
        } else if (cellType == CellType.NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                Date d = cell.getDateCellValue();
                value = defaultDateFormat.format(d);
            } else {
                value = numberFormat.format(cell.getNumericCellValue());
            }
        } else if (cellType == CellType.BOOLEAN) {
            value = cell.getBooleanCellValue() ? "true" : "false";
        } else if (cellType == CellType.BLANK) {
            value = null;
        }
    }
    return value;
}

From source file:de.topicmapslab.jexc.eXql.grammar.expression.FunctionExpression.java

License:Apache License

/**
 * Interpretation method for value function
 * //from   w w w .j  a v a2 s  .c o  m
 * @param workBook
 *            the workbook
 * @param row
 *            the row
 * @return the result value of the cell addressed by internal value
 *         expressions
 * @throws JeXcException
 *             thrown if operation fails
 */
private Object interpretValueFunction(Workbook workBook, Row row) throws JeXcException {
    if (getExpressions().size() != 2) {
        throw new JeXcException("Invalid number of contained value expression, expects 2 but was "
                + getExpressions().size() + ".");
    }
    Object oRowIndex = getExpressions().get(0).interpret(workBook, row);
    Object oColumnIndex = getExpressions().get(1).interpret(workBook, row);
    BigInteger rowIndex = LiteralUtils.asInteger(oRowIndex.toString());
    BigInteger columnIndex = LiteralUtils.asInteger(oColumnIndex.toString());
    Sheet sheet = row.getSheet();
    Row r = sheet.getRow(rowIndex.intValue());
    if (r == null) {
        return null;
    }
    Cell c = r.getCell(columnIndex.intValue());
    if (c == null) {
        return null;
    }
    if (c.getCellType() == Cell.CELL_TYPE_NUMERIC) {
        Double d = c.getNumericCellValue();
        Long l = d.longValue();
        /*
         * check if long value represents the same numeric value then the
         * double origin
         */
        if (d.doubleValue() == l.longValue()) {
            return String.valueOf(l);
        }
        return String.valueOf(d);
    } else if (c.getCellType() == Cell.CELL_TYPE_NUMERIC) {
        return c.getStringCellValue();
    } else if (c.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
        return c.getBooleanCellValue();
    }
    return c.getStringCellValue();
}

From source file:de.topicmapslab.jexc.eXql.grammar.expression.ValueExpression.java

License:Apache License

/**
 * Returns the cell value represent by the given token
 * /*from ww w.ja  v  a  2 s  . c o  m*/
 * @param cell
 *            the cell to extract the values from cell
 * @param token
 *            the token specifies the value to extract
 * @return the cell value
 * @throws JeXcException
 *             thrown if cell value token is unknown
 */
public Object getCellValue(final Cell cell, final String token) throws JeXcException {
    if (VALUE.equalsIgnoreCase(token) || VALUE_STRING.equalsIgnoreCase(token)) {
        switch (cell.getCellType()) {
        case Cell.CELL_TYPE_NUMERIC:
            Double d = cell.getNumericCellValue();
            Long l = d.longValue();
            /*
             * check if long value represents the same numeric value then
             * the double origin
             */
            if (d.doubleValue() == l.longValue()) {
                return String.valueOf(l);
            }
            return String.valueOf(d);
        case Cell.CELL_TYPE_BOOLEAN:
            return String.valueOf(cell.getBooleanCellValue());
        case Cell.CELL_TYPE_STRING:
        default:
            return cell.getStringCellValue();
        }
    } else if (VALUE_DATE.equalsIgnoreCase(token)) {
        return cell.getDateCellValue();
    } else if (VALUE_NUMERICAL.equalsIgnoreCase(token)) {
        return cell.getNumericCellValue();
    } else if (STYLE_FOREGROUND.equalsIgnoreCase(token)) {
        CellStyle style = cell.getCellStyle();
        return style == null ? NULL : style.getFillForegroundColor();
    } else if (STYLE_BACKGROUND.equalsIgnoreCase(token)) {
        CellStyle style = cell.getCellStyle();
        return style == null ? NULL : style.getFillBackgroundColor();
    } else if (BORDER_TOP.equalsIgnoreCase(token)) {
        CellStyle style = cell.getCellStyle();
        return style == null ? 0 : style.getBorderTop();
    } else if (BORDER_BOTTOM.equalsIgnoreCase(token)) {
        CellStyle style = cell.getCellStyle();
        return style == null ? 0 : style.getBorderBottom();
    } else if (BORDER_LEFT.equalsIgnoreCase(token)) {
        CellStyle style = cell.getCellStyle();
        return style == null ? 0 : style.getBorderLeft();
    } else if (BORDER_RIGHT.equalsIgnoreCase(token)) {
        CellStyle style = cell.getCellStyle();
        return style == null ? 0 : style.getBorderRight();
    } else if (ADDRESS.equalsIgnoreCase(token)) {
        StringBuilder builder = new StringBuilder();
        builder.append(cell.getSheet().getSheetName());
        builder.append(SLASH);
        builder.append(cell.getRow().getRowNum());
        builder.append(COLON);
        builder.append(cell.getColumnIndex());
        return builder.toString();
    } else if (HEIGHT.equalsIgnoreCase(token)) {
        CellRangeAddress address = XlsxCellUtils.getCellRange(cell);
        if (address != null) {
            return address.getLastRow() - address.getFirstRow() + 1;
        }
        return 1;
    } else if (ROW.equalsIgnoreCase(token)) {
        return cell.getRowIndex();
    } else if (COLUMN.equalsIgnoreCase(token)) {
        return cell.getColumnIndex();
    }
    throw new JeXcException("Unknown constant '" + token + "'!");
}

From source file:de.tum.in.socket.server.ReadExcel.java

License:Apache License

/**
 * Returns the type of value from a cell
 *//*w w w  . j  a  va 2s .c o  m*/
private static Object getTypeValue(final Class<?> type, final Cell cell) {
    Object typedValue = null;
    final DataFormatter formatter = new DataFormatter();
    if (type == int.class) {
        typedValue = (int) cell.getNumericCellValue();
    } else if (type == double.class) {
        typedValue = cell.getNumericCellValue();
    } else if (type == boolean.class) {
        typedValue = cell.getBooleanCellValue();
    } else if (type == String.class) {
        typedValue = formatter.formatCellValue(cell);
    }
    return typedValue;
}

From source file:demons.studentsmanagesystem.excel.poi.PoiSheet.java

License:Apache License

/**
 * {@inheritDoc}//  w  w  w .j a  v a 2  s . com
 */
@Override
public String[] getRow(final int rowNumber) {
    final Row row = this.delegate.getRow(rowNumber);
    if (row == null) {
        return null;
    }
    final List<String> cells = new LinkedList<String>();

    for (int i = 0; i < getNumberOfColumns(); i++) {
        Cell cell = row.getCell(i);
        switch (cell.getCellType()) {
        case Cell.CELL_TYPE_NUMERIC:
            if (DateUtil.isCellDateFormatted(cell)) {
                Date date = cell.getDateCellValue();
                cells.add(String.valueOf(date.getTime()));
            } else {
                cells.add(String.valueOf(cell.getNumericCellValue()));
            }
            break;
        case Cell.CELL_TYPE_BOOLEAN:
            cells.add(String.valueOf(cell.getBooleanCellValue()));
            break;
        case Cell.CELL_TYPE_STRING:
        case Cell.CELL_TYPE_BLANK:
            cells.add(cell.getStringCellValue());
            break;
        case Cell.CELL_TYPE_FORMULA:
            cells.add(getFormulaEvaluator().evaluate(cell).formatAsString());
            break;
        default:
            throw new IllegalArgumentException("Cannot handle cells of type " + cell.getCellType());
        }
    }
    return cells.toArray(new String[cells.size()]);
}

From source file:dias.m20150711_get_armband_data.java

public Matrix m20150711_get_armband_data() {

    eedouble = 0;/*  w w  w  .  j a  va  2 s .  com*/
    gsrdouble = 0;
    phys_actdouble = 0;
    sleepdouble = 0;

    try {
        FileInputStream file = new FileInputStream(new File(DIAS.bodymediaFileUrl));

        HSSFWorkbook workbook = new HSSFWorkbook(file);

        HSSFSheet sheet = workbook.getSheetAt(0);

        Iterator<Row> rowIterator = sheet.iterator();
        int s = 0;
        int i = 0;
        int j = 0;
        int kx = 0;
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            Iterator<org.apache.poi.ss.usermodel.Cell> cellIterator = row.cellIterator();
            i++;
            s = 0;
            while (cellIterator.hasNext()) {
                j++;
                org.apache.poi.ss.usermodel.Cell cell = cellIterator.next();
                switch (cell.getCellType()) {
                case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BOOLEAN:
                    break;
                case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_NUMERIC:
                    armband_data.set(i, j, cell.getNumericCellValue());

                    if (kx == 28)
                        armband_data_with_time.set(i, 5, cell.getNumericCellValue()); // Heat-Flux Average

                    if (kx == 27)
                        armband_data_with_time.set(i, 4, cell.getNumericCellValue()); //Sleep Classification

                    if (kx == 26)
                        armband_data_with_time.set(i, 3, cell.getNumericCellValue()); //Activity Class

                    if (kx == 25)
                        armband_data_with_time.set(i, 2, cell.getNumericCellValue()); //Distance

                    if (kx == 24)
                        armband_data_with_time.set(i, 1, cell.getNumericCellValue()); //Speed

                    if (kx == 23)
                        armband_data_with_time.set(i, 0, cell.getNumericCellValue()); //MET 's

                    kx++;

                    break;

                case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING:
                    if (cell.getStringCellValue().equals("NAN")) {
                        if (s == 0) {
                            i--;
                            s = 1;
                        }
                    }
                    break;
                }
            }
            kx = 0;
            j = 0;
        }

        file.close();
        s = 0;

        eedouble = 0;
        gsrdouble = 0;
        sleepdouble = 0;
        phys_actdouble = 0;

        eedouble = armband_data.get(7164, 18);
        gsrdouble = armband_data.get(7164, 14);
        sleepdouble = armband_data.get(7164, 16);
        phys_actdouble = armband_data.get(7164, 17);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return armband_data;

}

From source file:dk.cubing.liveresults.uploader.parser.WcaParser.java

License:Open Source License

/**
 * @param row/*from  ww  w .  j  av  a 2 s  .com*/
 * @param i
 * @return
 * @throws IllegalStateException
 */
private int parseResultCell(Row row, int i) throws IllegalStateException {
    int result = 0;
    Cell cell = row.getCell(3 + i);
    if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
        String cellStr = null;

        switch (cell.getCellType()) {
        // result values
        case Cell.CELL_TYPE_NUMERIC:
            // seconds
            if ("0.00".equals(cell.getCellStyle().getDataFormatString())) {
                result = new Double(cell.getNumericCellValue() * 100).intValue();

                // minutes
            } else if ("M:SS.00".equalsIgnoreCase(cell.getCellStyle().getDataFormatString())) {
                try {
                    result = resultTimeFormat.formatDateToInt(cell.getDateCellValue());
                } catch (ParseException e) {
                    log.error("[{}] " + e.getLocalizedMessage(), e);
                }

                // number
            } else if ("0".equals(cell.getCellStyle().getDataFormatString())) {
                result = new Double(cell.getNumericCellValue()).intValue();

                // unsupported
            } else {
                log.warn("[{}] Unsupported cell format: {}. Row/Column ({}, {})",
                        new Object[] { row.getSheet().getSheetName(), cell.getCellStyle().getDataFormatString(),
                                cell.getRowIndex(), cell.getColumnIndex() });
            }
            break;

        // Penalties
        case Cell.CELL_TYPE_STRING:
            cellStr = cell.getStringCellValue();
            if (cellStr != null) {
                if (cellStr.equalsIgnoreCase(Result.Penalty.DNF.toString())) {
                    result = Result.Penalty.DNF.getValue();
                } else if (cellStr.equalsIgnoreCase(Result.Penalty.DNS.toString())) {
                    result = Result.Penalty.DNS.getValue();
                }
            }
            break;

        // best / worst
        case Cell.CELL_TYPE_FORMULA:
            CellValue cellValue = evaluator.evaluate(cell);
            switch (cellValue.getCellType()) {
            // calculated value
            case Cell.CELL_TYPE_NUMERIC:
                // seconds
                if ("0.00".equals(cell.getCellStyle().getDataFormatString())) {
                    result = new Double(cellValue.getNumberValue() * 100).intValue();

                    // minutes
                } else if ("M:SS.00".equalsIgnoreCase(cell.getCellStyle().getDataFormatString())) {
                    try {
                        result = resultTimeFormat.formatDateToInt(cell.getDateCellValue());
                    } catch (ParseException e) {
                        log.error("[{}] " + e.getLocalizedMessage(), e);
                    }

                    // number
                } else if ("0".equals(cell.getCellStyle().getDataFormatString())
                        || "GENERAL".equals(cell.getCellStyle().getDataFormatString())) {
                    result = new Double(cell.getNumericCellValue()).intValue();

                    // unsupported
                } else {
                    log.warn("[{}] Unsupported cell format: {}. Row/Column ({}, {})",
                            new Object[] { row.getSheet().getSheetName(),
                                    cell.getCellStyle().getDataFormatString(), cell.getRowIndex(),
                                    cell.getColumnIndex() });
                }
                break;

            // Penalties
            case Cell.CELL_TYPE_STRING:
                cellStr = cellValue.getStringValue();
                if (cellStr != null) {
                    if (cellStr.equalsIgnoreCase(Result.Penalty.DNF.toString())) {
                        result = Result.Penalty.DNF.getValue();
                    } else if (cellStr.equalsIgnoreCase(Result.Penalty.DNS.toString())) {
                        result = Result.Penalty.DNS.getValue();
                    }
                }
                break;
            }
            break;
        }
    }
    return result;
}

From source file:domain.Excel.java

private static void showExelData(List sheetData) {

        ////from  w w w .  j a v  a2s  .  c  o  m
        // Iterates the data and print it out to the console.
        //
        for (int i = 0; i < sheetData.size(); i++) {

            List list = (List) sheetData.get(i);
            for (int j = 0; j < list.size(); j++) {

                Cell cell = (Cell) list.get(j);

                if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {

                    System.out.print(cell.getNumericCellValue());
                } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {

                    System.out.print(cell.getRichStringCellValue());
                } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {

                    System.out.print(cell.getBooleanCellValue());
                }
                if (j < list.size() - 1) {
                    System.out.print(", ");
                }
            }
            System.out.println("");
        }
    }

From source file:ec.mil.he1.mbeans.JSFManagedBeanFileUpload.java

public String convertjava() {
    grabar = "0";
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    try {//w ww .  j  av  a  2s. c  o  m
        connection = he1_pool.getConnection();

        String sql = "Insert into CODIGO_MIFIN(CEDULA, CODIGO, MES , MES_NUMERO, ANIO , DESCRIPCION, ARCHIVO)  Values   "
                + " (?, ?, ?, ? , ?, ? , ? )";
        int columna = 0;

        /*PrepareStatement*/
        preparedStatement = connection.prepareStatement(sql);

        //variables donde cargar los datos por cada celda
        String cc = "";
        String codigo = "";
        String mes = "";
        String mes_numero = "";
        String anio = "";
        String descripcion = "";

        file = (FileInputStream) inputstream;

        // Get the workbook instance for XLS file
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        sheet = workbook.getSheetAt(0);
        // Iterate through each rows from first sheet
        Iterator<org.apache.poi.ss.usermodel.Row> rowIterator = sheet.rowIterator();
        //aca se barre todas las filas
        while (rowIterator.hasNext()) {

            org.apache.poi.ss.usermodel.Row row = rowIterator.next();
            // For each row, iterate through each columns
            Iterator<Cell> cellIterator = row.cellIterator();
            //aca se tiene las columnas por ello encero
            columna = 0;
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();

                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_BOOLEAN:
                    cell.getBooleanCellValue();
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    cell.getNumericCellValue();
                    break;
                case Cell.CELL_TYPE_STRING:
                    cell.getStringCellValue();
                    break;
                }

                if (columna == 0) {
                    cc = cell.getStringCellValue();

                } else if (columna == 1) {
                    codigo = cell.getStringCellValue();

                } else if (columna == 2) {
                    mes = cell.getStringCellValue();

                } else if (columna == 3) {
                    mes_numero = cell.getStringCellValue();

                } else if (columna == 4) {
                    anio = cell.getStringCellValue();

                } else if (columna == 5) {
                    descripcion = cell.getStringCellValue();

                }

                columna++;
            }
            preparedStatement.setString(1, cc);
            preparedStatement.setString(2, codigo);
            preparedStatement.setString(3, mes);
            preparedStatement.setString(4, mes_numero);
            preparedStatement.setString(5, anio);
            preparedStatement.setString(6, descripcion);
            preparedStatement.setString(7, nombre_archivo);
            preparedStatement.addBatch();
            cc = "";
            codigo = "";
            mes = "";
            mes_numero = "";
            anio = "";
            descripcion = "";
            System.out.println("");
        }
        file.close();
        int[] affectedRecords = preparedStatement.executeBatch();
        addMessage("Se ha cargado la informacin en el sistema");

    } catch (IOException ex) {
        Logger.getLogger(JSFManagedBeanFileUpload.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(JSFManagedBeanFileUpload.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
                preparedStatement = null;
            } catch (SQLException ex) {
                Logger.getLogger(JSFManagedBeanFileUpload.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (connection != null) {
            try {
                connection.close();
                connection = null;
            } catch (SQLException ex) {
                Logger.getLogger(JSFManagedBeanFileUpload.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return null;
}

From source file:edms.core.Config.java

License:Open Source License

public static void convertToXlsx(InputStream inStream, java.io.File outputFile) {
    // For storing data into CSV files
    StringBuffer cellValue = new StringBuffer();
    try {//from  w  w w  .j a  v  a  2  s.  com
        FileOutputStream fos = new FileOutputStream(outputFile);

        // Get the workbook instance for XLSX file
        XSSFWorkbook wb = new XSSFWorkbook(inStream);

        // Get first sheet from the workbook
        XSSFSheet sheet = wb.getSheetAt(0);

        Row row;
        Cell cell;

        // Iterate through each rows from first sheet
        Iterator<Row> rowIterator = sheet.iterator();

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

            // For each row, iterate through each columns
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                cell = cellIterator.next();

                switch (cell.getCellType()) {

                case Cell.CELL_TYPE_BOOLEAN:
                    cellValue.append(cell.getBooleanCellValue() + ",");
                    break;

                case Cell.CELL_TYPE_NUMERIC:
                    cellValue.append(cell.getNumericCellValue() + ",");
                    break;

                case Cell.CELL_TYPE_STRING:
                    cellValue.append(cell.getStringCellValue() + ",");
                    break;

                case Cell.CELL_TYPE_BLANK:
                    cellValue.append("" + ",");
                    break;

                default:
                    cellValue.append(cell + ",");

                }
            }
        }

        fos.write(cellValue.toString().getBytes());

        fos.close();

    } catch (Exception e) {
        System.err.println("Exception :" + e.getMessage());
    }

}