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:edms.core.Config.java

License:Open Source License

public static void convertToXls(InputStream inStream, java.io.File outputFile) {
    // For storing data into CSV files
    StringBuffer cellDData = new StringBuffer();
    try {/*w  w  w .j  av  a 2  s  .  c o  m*/
        FileOutputStream fos = new FileOutputStream(outputFile);

        // Get the workbook instance for XLS file
        HSSFWorkbook workbook = new HSSFWorkbook(inStream);
        // Get first sheet from the workbook
        HSSFSheet sheet = workbook.getSheetAt(0);
        Cell cell;
        Row row;

        // 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:
                    cellDData.append(cell.getBooleanCellValue() + ",");
                    break;

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

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

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

                default:
                    cellDData.append(cell + ",");
                }
            }
        }

        fos.write(cellDData.toString().getBytes());
        fos.close();

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

}

From source file:edu.emory.cci.aiw.cvrg.eureka.etl.spreadsheet.XlsxDataProvider.java

License:Open Source License

/**
 * Read a string value from the given cell.
 *
 * @param cell The cell to read value from.
 * @return A String containing the cell value, if valid, null otherwise.
 */// w w  w.  j  av  a  2 s. c  o m
private String readStringValue(String sheetName, Cell cell) throws DataProviderException {
    String result = null;
    if (cell != null) {
        try {
            int cellType = cell.getCellType();
            if (cellType == Cell.CELL_TYPE_STRING) {
                result = cell.getStringCellValue();
            } else if (cellType == Cell.CELL_TYPE_NUMERIC) {
                result = Double.toString(cell.getNumericCellValue());
            } else if (cellType == Cell.CELL_TYPE_BOOLEAN) {
                result = Boolean.toString(cell.getBooleanCellValue());
            } else {
                throwException(sheetName, cell, "Cell type must be a number, string, boolean or blank");
            }
        } catch (Exception e) {
            throwException(sheetName, cell, e.getMessage(), e);
        }
    }
    return result;
}

From source file:edu.emory.cci.aiw.cvrg.eureka.etl.spreadsheet.XlsxDataProvider.java

License:Open Source License

/**
 * Read a numerical value as a Long type from the given cell.
 *
 * @param cell The cell to read the value from.
 * @return A Long containing the cell's value, if valid, null otherwise.
 *//*  ww w.ja  va 2  s  .co m*/
private Long readLongValue(String sheetName, Cell cell) throws DataProviderException {
    Long result = null;
    if (cell != null) {
        try {
            Double value = new Double(cell.getNumericCellValue());
            result = Long.valueOf(value.longValue());
        } catch (Exception e) {
            throwException(sheetName, cell, e.getMessage(), e);
        }
    }
    return result;
}

From source file:edu.emory.cci.aiw.cvrg.eureka.etl.spreadsheet.XlsxDataProvider.java

License:Open Source License

/**
 * Read the give cell's value as a Double type.
 *
 * @param cell The cell to read the value from.
 * @return A Double containing the cell value, if valid, null otherwise.
 *///from  ww  w  .  j ava2  s . com
private Double readDoubleValue(String sheetName, Cell cell) throws DataProviderException {
    Double result = null;
    if (cell != null) {
        try {
            double value = cell.getNumericCellValue();
            result = Double.valueOf(value);
        } catch (Exception e) {
            throwException(sheetName, cell, e.getMessage(), e);
        }
    }
    return result;
}

From source file:edu.gatech.pmase.capstone.awesome.impl.database.AbstractDatabaseDriver.java

License:Open Source License

/**
 * Reads in a List of IDs contained within a Cell.
 *
 * @param cell the Cell to read from//from w  w w  .  ja  v a 2 s .c o m
 *
 * @return a List of ID's contained within the given Cell.
 */
protected List<Long> getListFromCell(final Cell cell) {
    List<Long> result = new ArrayList<>(1);
    if (null != cell && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            final String[] split = cell.getStringCellValue().replaceAll(" ", "").split(LIST_STRING_SPLIT_REGEX);
            // check if single value
            if (null != split && split.length > 0) {
                result = Arrays.asList(split).stream().map((String str) -> Long.parseLong(str))
                        .collect(Collectors.toList());
            } else {
                LOGGER.error("Invalid List of values found in DB in cell: [" + cell.getRowIndex() + ","
                        + cell.getColumnIndex() + "]");
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            result.add((long) cell.getNumericCellValue());
        }
    }
    return result;
}

From source file:edu.gatech.pmase.capstone.awesome.impl.database.AbstractDatabaseDriver.java

License:Open Source License

/**
 * Gets the custom attributes from the given row.
 *
 * @param row the row to read from//  w ww  . j a  va 2  s . c om
 *
 * @return the list of gathered custom attributes.
 */
protected List<ArchitectureOptionAttribute> getCustomAttributes(final Row row) {
    final List<ArchitectureOptionAttribute> attrList = new ArrayList<>(customAttributes.size());
    final StringBuilder attrLabels = new StringBuilder();

    for (final ArchitectureOptionAttribute attr : customAttributes) {
        final Cell cell = row.getCell(attr.getColNum());
        try {
            final ArchitectureOptionAttribute cpy = new ArchitectureOptionAttribute(attr);

            if (cpy.getType().equals(String.class)) {
                cpy.setValue(cell.getStringCellValue());
                cpy.setOriginalValue(cell.getStringCellValue());
            } else if (cpy.getType().equals(Double.class)) {
                cpy.setValue(cell.getNumericCellValue());
                cpy.setOriginalValue(cell.getNumericCellValue());
            } else {
                LOGGER.warn("Unable to read custom attributes for row: " + row.getRowNum()
                        + ". Unknown cell type: " + cpy.getType().getName());
            }

            attrList.add(cpy);

            if (attrList.isEmpty()) {
                attrLabels.append("--");
            } else {
                attrLabels.append(", ");
            }
            attrLabels.append(cpy.getLabel());
        } catch (ClassNotFoundException ex) {
            LOGGER.warn("Unable to read custom attributes for row: " + row.getRowNum(), ex);
        }
    }

    LOGGER.debug("Read " + attrList.size() + " custom attributes for row: " + row.getRowNum()
            + attrLabels.toString());
    return attrList;
}

From source file:edu.gatech.pmase.capstone.awesome.impl.database.CommunicationsDatabaseDriver.java

License:Open Source License

@Override
protected CommunicationOption getOptionFromRow(final Row row) {
    CommunicationOption option = null;/*from www  .  j  av a2s.co m*/

    // load required info
    final Cell idCell = row.getCell(ID_CELL_NUM);
    final Cell labelCell = row.getCell(LABEL_CELL_NUM);
    final Cell costRankCell = row.getCell(COST_RANK_CELL_NUM);
    final Cell weightCell = row.getCell(WEIGHT_CELL_NUM);

    if (null == idCell || null == labelCell || null == costRankCell || null == weightCell) {
        LOGGER.trace(
                "Comm Database Row " + row.getRowNum() + " missing required CommunicationsOption information.");
    } else {
        option = new CommunicationOption();
        final long idNum = (long) idCell.getNumericCellValue();
        LOGGER.debug("Parsing CommunicationsOption with ID: " + idNum);

        option.setId(idNum);
        option.setLabel(labelCell.getStringCellValue());
        option.setCostRanking((int) costRankCell.getNumericCellValue());
        option.setWeight(weightCell.getNumericCellValue());

        // get custom attributes
        option.setCustomAttributes(this.getCustomAttributes(row));

        // load optional info
        // platform restrictions
        option.setPlatformLimitations(
                this.getPlatFormRestrictFromCell(row.getCell(PLAT_RESTRICT_CELL_NUM), platformOptions));

        // terrain effects
        final List<TerrainEffect> terrainLimitation = new ArrayList<>();
        terrainLimitation.addAll(this.getTerrainEffectsFromCell(row.getCell(TERRAIN_ONE_RESTRICT_CELL_NUM), 1));
        terrainLimitation.addAll(this.getTerrainEffectsFromCell(row.getCell(TERRAIN_TWO_RESTRICT_CELL_NUM), 2));
        terrainLimitation
                .addAll(this.getTerrainEffectsFromCell(row.getCell(TERRAIN_THREE_RESTRICT_CELL_NUM), 3));
        terrainLimitation
                .addAll(this.getTerrainEffectsFromCell(row.getCell(TERRAIN_FOUR_RESTRICT_CELL_NUM), 4));

        LOGGER.debug("Found " + terrainLimitation.size()
                + " total Terrian Effect Restrictions for CommunicationsOption");

        option.setTerrainLimitation(terrainLimitation);

        // disaster effect restrictions
        option.setDisasterLimitations(
                this.getDisasterEffectRestrictFromCell(row.getCell(DISASTER_EFFECT_RESTRICT_CELL_NUM)));
    }

    return option;
}

From source file:edu.gatech.pmase.capstone.awesome.impl.database.PlatformDatabaseDriver.java

License:Open Source License

/**
 * Creates a PlatformOption from a row.//from  w w w.  j a v  a  2s.c  o  m
 *
 * @param row the row to transform
 *
 * @return the created PlatformOption, or null if cannot read the row.
 */
@Override
protected PlatformOption getOptionFromRow(Row row) {
    PlatformOption option = null;

    // load required info
    final Cell idCell = row.getCell(ID_CELL_NUM);
    final Cell labelCell = row.getCell(LABEL_CELL_NUM);
    final Cell typeCell = row.getCell(TYPE_CELL_NUM);
    final Cell costRankCell = row.getCell(COST_RANKING_CELL_NUM);
    final Cell payloadCell = row.getCell(PAYLOAD_CELL_NUM);

    if (null == idCell || null == labelCell || null == typeCell || null == costRankCell || null == payloadCell
            || idCell.getCellType() == Cell.CELL_TYPE_BLANK) {
        LOGGER.trace(
                "Platform Database Row " + row.getRowNum() + " missing required PlatformOption information.");
    } else {
        option = new PlatformOption();
        final long idNum = (long) idCell.getNumericCellValue();
        LOGGER.debug("Parsing PlatformOption with ID: " + idNum);

        option.setId(idNum);
        option.setLabel(labelCell.getStringCellValue());
        option.setCostRanking((int) costRankCell.getNumericCellValue());
        option.setPayload(payloadCell.getNumericCellValue());

        // set Platform Type
        option.setPlatformType(PlatformDatabaseDriver.getPlatformType(typeCell));

        // set custom attributes
        option.setCustomAttributes(this.getCustomAttributes(row));

        // load optional info
        // terrain effects
        final List<TerrainEffect> terrainLimitation = new ArrayList<>();
        terrainLimitation.addAll(this.getTerrainEffectsFromCell(row.getCell(TERRAIN_ONE_RESTRICT_CELL_NUM), 1));
        terrainLimitation.addAll(this.getTerrainEffectsFromCell(row.getCell(TERRAIN_TWO_RESTRICT_CELL_NUM), 2));
        terrainLimitation
                .addAll(this.getTerrainEffectsFromCell(row.getCell(TERRAIN_THREE_RESTRICT_CELL_NUM), 3));
        terrainLimitation
                .addAll(this.getTerrainEffectsFromCell(row.getCell(TERRAIN_FOUR_RESTRICT_CELL_NUM), 4));

        LOGGER.debug(
                "Found " + terrainLimitation.size() + " total Terrian Effect Restrictions for PlatformOption");

        option.setTerrainLimitation(terrainLimitation);

        // disaster effect restrictions
        option.setDisasterLimitations(
                this.getDisasterEffectRestrictFromCell(row.getCell(DISASTER_EFFECT_RESTRICT_CELL_NUM)));
    }

    return option;
}

From source file:edu.gatech.pmase.capstone.awesome.impl.database.SensorsDatabaseDriver.java

License:Open Source License

/**
 * Creates a SensorOption from a row.//from   w w  w . ja  v  a2 s.c  o m
 *
 * @param row the row to transform
 *
 * @return the created SensorOption, or null if cannot read the row.
 */
@Override
protected SensorOption getOptionFromRow(final Row row) {
    SensorOption option = null;

    // load required info
    final Cell idCell = row.getCell(ID_CELL_NUM);
    final Cell labelCell = row.getCell(LABEL_CELL_NUM);
    final Cell costRankCell = row.getCell(COST_RANK_CELL_NUM);
    final Cell weightCell = row.getCell(WEIGHT_CELL_NUM);

    if (null == idCell || null == labelCell || null == costRankCell || null == weightCell
            || idCell.getCellType() == Cell.CELL_TYPE_BLANK) {
        LOGGER.trace("Sensor Database Row " + row.getRowNum() + " missing required SensorOption information.");
    } else {
        option = new SensorOption();
        final long idNum = (long) idCell.getNumericCellValue();
        LOGGER.debug("Parsing SensorOption with ID: " + idNum);

        option.setId(idNum);
        option.setLabel(labelCell.getStringCellValue());
        option.setCostRanking((int) costRankCell.getNumericCellValue());
        option.setWeight(weightCell.getNumericCellValue());

        // set custom attributes
        option.setCustomAttributes(this.getCustomAttributes(row));

        // load optional info
        // platform restrictions
        option.setPlatformLimitations(
                this.getPlatFormRestrictFromCell(row.getCell(PLAT_RESTRICT_CELL_NUM), platformOptions));

        // terrain effects
        final List<TerrainEffect> terrainLimitation = new ArrayList<>();
        terrainLimitation.addAll(this.getTerrainEffectsFromCell(row.getCell(TERRAIN_ONE_RESTRICT_CELL_NUM), 1));
        terrainLimitation.addAll(this.getTerrainEffectsFromCell(row.getCell(TERRAIN_TWO_RESTRICT_CELL_NUM), 2));
        terrainLimitation
                .addAll(this.getTerrainEffectsFromCell(row.getCell(TERRAIN_THREE_RESTRICT_CELL_NUM), 3));
        terrainLimitation
                .addAll(this.getTerrainEffectsFromCell(row.getCell(TERRAIN_FOUR_RESTRICT_CELL_NUM), 4));

        LOGGER.debug(
                "Found " + terrainLimitation.size() + " total Terrian Effect Restrictions for SensorOption");

        option.setTerrainLimitation(terrainLimitation);

        // disaster effect restrictions
        option.setDisasterLimitations(
                this.getDisasterEffectRestrictFromCell(row.getCell(DISASTER_EFFECT_RESTRICT_CELL_NUM)));
    }

    return option;
}

From source file:edu.jhu.pha.vospace.process.tika.ExcelParser.java

License:Apache License

@Override
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {

    XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
    xhtml.startDocument();/*from  w  w w .  j a  v  a2  s . c om*/

    Workbook wb;

    try {
        wb = WorkbookFactory.create(stream);
    } catch (InvalidFormatException e) {
        throw new TikaException("Invalid format");
    }

    Sheet sheet = wb.getSheetAt(0);
    int nRows = sheet.getLastRowNum();
    int nCols = sheet.getRow(0).getLastCellNum();
    xhtml.startElement("section", "id", String.valueOf(1));

    AttributesImpl attributes = new AttributesImpl();
    //attributes.addAttribute("", "id", "id", "CDATA", String.valueOf(1));
    attributes.addAttribute("", "columns", "columns", "CDATA", String.valueOf(nCols));
    xhtml.startElement("table", attributes);

    Row headerRow = sheet.getRow(0);
    xhtml.startElement("th", "info", "columnNames");
    for (int j = 0; j < nCols; j++) {
        Cell cell = headerRow.getCell(j);
        String columnName = cell.getStringCellValue();
        xhtml.element("td", columnName);
    }
    xhtml.endElement("th");
    Row firstDataRow = sheet.getRow(1);
    xhtml.startElement("th", "info", "columnTypes");
    for (int j = 0; j < nCols; j++) {
        Cell cell = firstDataRow.getCell(j);
        int type = cell.getCellType();
        String columnType = null;
        switch (type) {
        case Cell.CELL_TYPE_NUMERIC:
            columnType = "D";
            break;
        case Cell.CELL_TYPE_STRING:
            columnType = "A";
            break;
        }
        xhtml.element("td", columnType);
    }
    xhtml.endElement("th");

    for (int i = 1; i <= nRows; i++) {
        Row row = sheet.getRow(i);
        xhtml.startElement("tr");
        for (int j = 0; j < nCols; j++) {
            Cell cell = row.getCell(j);
            int type = cell.getCellType();
            switch (type) {
            case Cell.CELL_TYPE_NUMERIC:
                xhtml.element("td", String.valueOf(cell.getNumericCellValue()));
                break;
            case Cell.CELL_TYPE_STRING:
                xhtml.element("td", cell.getStringCellValue());
                break;
            }
        }
        xhtml.endElement("tr");

    }
    xhtml.endElement("table");
    xhtml.endElement("section");
    xhtml.endDocument();

    metadata.add(TikaCoreProperties.TYPE, "EXCEL");
}