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

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

Introduction

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

Prototype

CellStyle getCellStyle();

Source Link

Document

Return the cell's style.

Usage

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

License:Open Source License

private String getCachedFormulaCellValue(Cell formulaCell) {
    String result = null;/*w w w  .jav  a  2 s.  c om*/
    switch (formulaCell.getCachedFormulaResultType()) {
    case Cell.CELL_TYPE_STRING:
        result = formulaCell.getStringCellValue();
        break;
    case Cell.CELL_TYPE_BOOLEAN:
        result = String.valueOf(formulaCell.getBooleanCellValue());
        break;
    case Cell.CELL_TYPE_ERROR:
        result = ErrorEval.getText(formulaCell.getErrorCellValue());
        break;
    case Cell.CELL_TYPE_NUMERIC:
        CellStyle style = formulaCell.getCellStyle();
        result = formatter.formatRawCellContents(formulaCell.getNumericCellValue(), style.getDataFormat(),
                style.getDataFormatString());
        break;
    }
    return result;
}

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

License:Open Source License

protected CellData createCellDataForCell(Cell cell) {
    CellData cellData = new CellData();
    cellData.row = cell.getRowIndex() + 1;
    cellData.col = cell.getColumnIndex() + 1;
    CellStyle cellStyle = cell.getCellStyle();
    cellData.cellStyle = "cs" + cellStyle.getIndex();
    cellData.locked = spreadsheet.isCellLocked(cell);
    try {//from   w  ww  .  j  a va2 s .c o m
        if (!spreadsheet.isCellHidden(cell)) {
            if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
                cellData.formulaValue = formulaFormatter.reFormatFormulaValue(cell.getCellFormula(),
                        spreadsheet.getLocale());
                try {
                    String oldValue = getCachedFormulaCellValue(cell);
                    String newValue = formatter.formatCellValue(cell, getFormulaEvaluator());
                    if (!newValue.equals(oldValue)) {
                        changedFormulaCells.add(new CellReference(cell));
                    }
                } catch (RuntimeException rte) {
                    // Apache POI throws RuntimeExceptions for an invalid
                    // formula from POI model
                    String formulaValue = cell.getCellFormula();
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    cell.setCellValue(formulaValue);
                    spreadsheet.markInvalidFormula(cell.getColumnIndex() + 1, cell.getRowIndex() + 1);
                }

            }
        }

        if (cell.getCellStyle().getDataFormatString().contains("%")) {
            cellData.isPercentage = true;
        }

        String formattedCellValue = formatter.formatCellValue(cell, getFormulaEvaluator());

        if (!spreadsheet.isCellHidden(cell)) {
            if (cell.getCellType() == Cell.CELL_TYPE_FORMULA || cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                formattedCellValue = formattedCellValue.replaceAll("^-(?=0(.0*)?$)", "");
            }
        }
        if (spreadsheet.isMarkedAsInvalidFormula(cellData.col, cellData.row)) {
            // The prefix '=' or '+' should not be included in formula value
            if (cell.getStringCellValue().charAt(0) == '+' || cell.getStringCellValue().charAt(0) == '=') {
                cellData.formulaValue = cell.getStringCellValue().substring(1);
            }
            formattedCellValue = "#VALUE!";
        }

        if (formattedCellValue != null && !formattedCellValue.isEmpty() || cellStyle.getIndex() != 0) {
            // if the cell is not wrapping text, and is of type numeric or
            // formula (but not date), calculate if formatted cell value
            // fits the column width and possibly use scientific notation.
            cellData.value = formattedCellValue;
            cellData.needsMeasure = false;
            if (!cellStyle.getWrapText()
                    && (!SpreadsheetUtil.cellContainsDate(cell) && cell.getCellType() == Cell.CELL_TYPE_NUMERIC
                            || cell.getCellType() == Cell.CELL_TYPE_STRING
                            || (cell.getCellType() == Cell.CELL_TYPE_FORMULA
                                    && !cell.getCellFormula().startsWith("HYPERLINK")))) {
                if (!doesValueFit(cell, formattedCellValue)) {
                    if (valueContainsOnlyNumbers(formattedCellValue) && isGenerallCell(cell)) {
                        cellData.value = cellValueFormatter.getScientificNotationStringForNumericCell(
                                cell.getNumericCellValue(), formattedCellValue,
                                cellStyleWidthRatioMap.get((int) cell.getCellStyle().getIndex()),
                                spreadsheet.getState(false).colW[cell.getColumnIndex()] - 10);
                    } else if (cell.getCellType() != Cell.CELL_TYPE_STRING) {
                        cellData.needsMeasure = true;
                    }
                }
            }

            if (cellStyle.getAlignment() == CellStyle.ALIGN_RIGHT) {
                cellData.cellStyle = cellData.cellStyle + " r";
            } else if (cellStyle.getAlignment() == CellStyle.ALIGN_GENERAL) {
                if (SpreadsheetUtil.cellContainsDate(cell) || cell.getCellType() == Cell.CELL_TYPE_NUMERIC
                        || (cell.getCellType() == Cell.CELL_TYPE_FORMULA
                                && !cell.getCellFormula().startsWith("HYPERLINK")
                                && !(cell.getCachedFormulaResultType() == Cell.CELL_TYPE_STRING))) {
                    cellData.cellStyle = cellData.cellStyle + " r";
                }
            }

        }

        // conditional formatting might be applied even if there isn't a
        // value (such as borders for the cell to the right)
        Set<Integer> cellFormattingIndexes = spreadsheet.getConditionalFormatter().getCellFormattingIndex(cell);
        if (cellFormattingIndexes != null) {

            for (Integer i : cellFormattingIndexes) {
                cellData.cellStyle = cellData.cellStyle + " cf" + i;
            }

            markedCells.add(SpreadsheetUtil.toKey(cell));
        }

        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC && DateUtil.isCellDateFormatted(cell)) {
            cellData.originalValue = cellData.value;
        } else {
            cellData.originalValue = getOriginalCellValue(cell);
        }

        handleIsDisplayZeroPreference(cell, cellData);
    } catch (RuntimeException rte) {
        LOGGER.log(Level.FINEST, rte.getMessage(), rte);
        cellData.value = "#VALUE!";
    }

    return cellData;
}

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

License:Open Source License

/**
 * Check if the given cell is a numeric cell, and specifically the data
 * format is "General". In Excel and Spreadsheet this is the default type
 * for cells.// w  ww. j  ava2  s .c o m
 */
private boolean isGenerallCell(Cell cell) {
    return cell.getCellType() == Cell.CELL_TYPE_NUMERIC
            && cell.getCellStyle().getDataFormatString().contains("General");
}

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

License:Open Source License

private boolean doesValueFit(Cell cell, String value) {
    Float r = cellStyleWidthRatioMap.get((int) cell.getCellStyle().getIndex());
    if (r == null) {
        return true;
    }/*from  w  w w  .  j ava  2 s.  c  o m*/
    BigDecimal ratio = new BigDecimal(r);
    BigDecimal stringPixels = ratio.multiply(new BigDecimal(value.length()));
    // The -4 here is for 2px cell left/right padding
    // FIXME We should probably measure this from the actual value since it
    // might be changed in the style
    BigDecimal columnWidth = new BigDecimal(spreadsheet.getState(false).colW[cell.getColumnIndex()] - 4);
    return stringPixels.compareTo(columnWidth) <= 0;
}

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

License:Open Source License

/**
 * Updates the cell value and type, causes a recalculation of all the values
 * in the cell.//w  ww .  j a  v a 2  s .  c  om
 *
 * If there is a {@link CellValueHandler} defined, then it is used.
 *
 * Cells starting with "=" or "+" will be created/changed into FORMULA type.
 *
 * Cells that are existing and are NUMERIC type will be parsed according to
 * their existing format, or if that fails, as Double.
 *
 * Cells not containing any letters and containing at least one number will
 * be created/changed into NUMERIC type (formatting is not changed).
 *
 * Existing Boolean cells will be parsed as Boolean.
 *
 * For everything else and if any of the above fail, the cell will get the
 * STRING type and the value will just be a string, except empty values will
 * cause the cell type to be BLANK.
 *
 * @param col
 *            Column index of target cell, 1-based
 * @param row
 *            Row index of target cell, 1-based
 * @param value
 *            The new value to set to the target cell, formulas will start
 *            with an extra "=" or "+"
 */
public void onCellValueChange(int col, int row, String value) {
    Workbook workbook = spreadsheet.getWorkbook();
    // update cell value
    final Sheet activeSheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
    Row r = activeSheet.getRow(row - 1);
    if (r == null) {
        r = activeSheet.createRow(row - 1);
    }
    Cell cell = r.getCell(col - 1);
    String formattedCellValue = null;
    int oldCellType = -1;
    // capture cell value to history
    CellValueCommand command = new CellValueCommand(spreadsheet);
    command.captureCellValues(new CellReference(row - 1, col - 1));
    spreadsheet.getSpreadsheetHistoryManager().addCommand(command);
    boolean updateHyperlinks = false;

    if (getCustomCellValueHandler() == null || getCustomCellValueHandler().cellValueUpdated(cell, activeSheet,
            col - 1, row - 1, value, getFormulaEvaluator(), formatter)) {
        Exception exception = null;
        try {
            // handle new cell creation
            SpreadsheetStyleFactory styler = spreadsheet.getSpreadsheetStyleFactory();
            final Locale spreadsheetLocale = spreadsheet.getLocale();
            if (cell == null) {
                cell = r.createCell(col - 1);
            } else {
                // modify existing cell, possibly switch type
                formattedCellValue = getFormattedCellValue(cell);
                final String key = SpreadsheetUtil.toKey(col, row);
                oldCellType = cell.getCellType();
                if (!sentCells.remove(key)) {
                    sentFormulaCells.remove(key);
                }

                // Old value was hyperlink => needs refresh
                if (cell.getCellType() == Cell.CELL_TYPE_FORMULA
                        && cell.getCellFormula().startsWith("HYPERLINK")) {
                    updateHyperlinks = true;
                }
            }
            if (formulaFormatter.isFormulaFormat(value)) {
                if (formulaFormatter.isValidFormulaFormat(value, spreadsheetLocale)) {
                    spreadsheet.removeInvalidFormulaMark(col, row);
                    getFormulaEvaluator().notifyUpdateCell(cell);
                    cell.setCellType(Cell.CELL_TYPE_FORMULA);
                    cell.setCellFormula(
                            formulaFormatter.unFormatFormulaValue(value.substring(1), spreadsheetLocale));
                    getFormulaEvaluator().notifySetFormula(cell);
                    if (value.startsWith("=HYPERLINK(")
                            && cell.getCellStyle().getIndex() != hyperlinkStyleIndex) {
                        // set the cell style to link cell
                        CellStyle hyperlinkCellStyle;
                        if (hyperlinkStyleIndex == -1) {
                            hyperlinkCellStyle = styler.createHyperlinkCellStyle();
                            hyperlinkStyleIndex = -1;
                        } else {
                            hyperlinkCellStyle = workbook.getCellStyleAt(hyperlinkStyleIndex);
                        }
                        cell.setCellStyle(hyperlinkCellStyle);
                        styler.cellStyleUpdated(cell, true);
                        updateHyperlinks = true;
                    }
                } else {
                    // it's formula but invalid
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    cell.setCellValue(value);
                    spreadsheet.markInvalidFormula(col, row);
                }
            } else {
                spreadsheet.removeInvalidFormulaMark(col, row);
                Double percentage = SpreadsheetUtil.parsePercentage(value, spreadsheetLocale);
                Double numVal = SpreadsheetUtil.parseNumber(cell, value, spreadsheetLocale);
                if (value.isEmpty()) {
                    cell.setCellType(Cell.CELL_TYPE_BLANK);
                } else if (percentage != null) {
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    CellStyle cs = cell.getCellStyle();
                    if (cs == null) {
                        cs = workbook.createCellStyle();
                        cell.setCellStyle(cs);
                    }

                    if (cs.getDataFormatString() != null && !cs.getDataFormatString().contains("%")) {
                        cs.setDataFormat(workbook.createDataFormat()
                                .getFormat(spreadsheet.getDefaultPercentageFormat()));
                        styler.cellStyleUpdated(cell, true);
                    }
                    cell.setCellValue(percentage);
                } else if (numVal != null) {
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(numVal);
                } else if (oldCellType == Cell.CELL_TYPE_BOOLEAN) {
                    cell.setCellValue(Boolean.parseBoolean(value));
                } else {
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    cell.setCellValue(value);
                }
                getFormulaEvaluator().notifyUpdateCell(cell);
            }

        } catch (FormulaParseException fpe) {
            try {
                exception = fpe;

                // parses formula
                cell.setCellFormula(value.substring(1).replace(" ", ""));
            } catch (FormulaParseException fpe2) {
                exception = fpe2;
                /*
                 * We could force storing the formula even if it is invalid.
                 * Instead, just store it as the value. Clearing the formula
                 * makes sure the value is displayed as-is.
                 */
                cell.setCellType(Cell.CELL_TYPE_STRING);
                cell.setCellValue(value);
                spreadsheet.markInvalidFormula(col, row);
            }
        } catch (NumberFormatException nfe) {
            exception = nfe;
            cell.setCellValue(value);
        } catch (Exception e) {
            exception = e;
            cell.setCellValue(value);
        }
        if (cell != null) {
            markCellForUpdate(cell);
            if (formattedCellValue == null || !formattedCellValue.equals(getFormattedCellValue(cell))
                    || oldCellType != cell.getCellType()) {
                fireCellValueChangeEvent(cell);
            }
        }
        if (exception != null) {
            LOGGER.log(Level.FINE, "Failed to parse cell value for cell at col " + col + " row " + row + " ("
                    + exception.getMessage() + ")", exception);
        }
    }

    spreadsheet.updateMarkedCells();

    if (updateHyperlinks) {
        spreadsheet.loadHyperLinks();
    }
}

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

License:Open Source License

/**
 * Attempts to parse a numeric value from the given String and set it to the
 * given Cell.//from ww w. j a  v a2  s  . c o m
 *
 * @param cell
 *            Target Cell
 * @param value
 *            Source for parsing the value
 */
protected void parseValueIntoNumericCell(final Cell cell, final String value) {
    // try to parse the string with the existing cell format
    Format oldFormat = formatter.createFormat(cell);
    if (oldFormat != null) {
        try {
            final Object parsedObject = oldFormat.parseObject(value);
            if (parsedObject instanceof Date) {
                cell.setCellValue((Date) parsedObject);
            } else if (parsedObject instanceof Calendar) {
                cell.setCellValue((Calendar) parsedObject);
            } else if (parsedObject instanceof Number) {
                cell.setCellValue(((Number) parsedObject).doubleValue());
            } else {
                cell.setCellValue(Double.parseDouble(value));
            }
        } catch (ParseException pe) {
            LOGGER.log(Level.FINEST, "Could not parse String to format, " + oldFormat.getClass() + ", "
                    + cell.getCellStyle().getDataFormatString() + " : " + pe.getMessage(), pe);
            try {
                cell.setCellValue(Double.parseDouble(value));
            } catch (NumberFormatException nfe) {
                LOGGER.log(Level.FINEST, "Could not parse String to Double: " + nfe.getMessage(), nfe);
                cell.setCellValue(value);
            }
        } catch (NumberFormatException nfe) {
            LOGGER.log(Level.FINEST, "Could not parse String to Double: " + nfe.getMessage(), nfe);
            cell.setCellValue(value);
        }
    }
}

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

License:Open Source License

/**
 * Method for updating cells that are marked for update and formula cells.
 *
 * Iterates over the whole sheet (existing rows and columns) and updates
 * client side cache for all sent formula cells, and cells that have been
 * marked for updating./*from w w  w.  jav  a  2s . c o m*/
 *
 */
protected void updateMarkedCellValues() {
    final ArrayList<CellData> updatedCellData = new ArrayList<CellData>();
    Sheet sheet = spreadsheet.getActiveSheet();
    // it is unnecessary to worry about having custom components in the cell
    // because the client side handles it -> it will not replace a custom
    // component with a cell value

    // update all cached formula cell values on client side, because they
    // might have changed. also make sure all marked cells are updated
    Iterator<Row> rows = sheet.rowIterator();
    while (rows.hasNext()) {
        final Row r = rows.next();
        final Iterator<Cell> cells = r.cellIterator();
        while (cells.hasNext()) {
            final Cell cell = cells.next();
            int rowIndex = cell.getRowIndex();
            int columnIndex = cell.getColumnIndex();
            final String key = SpreadsheetUtil.toKey(columnIndex + 1, rowIndex + 1);
            CellData cd = createCellDataForCell(cell);
            // update formula cells
            if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
                if (cd != null) {
                    if (sentFormulaCells.contains(key) || markedCells.contains(key)) {
                        sentFormulaCells.add(key);
                        updatedCellData.add(cd);
                    }
                } else if (sentFormulaCells.contains(key)) {
                    // in case the formula cell value has changed to null or
                    // empty; this case is probably quite rare, formula cell
                    // pointing to a cell that was removed or had its value
                    // cleared ???
                    sentFormulaCells.add(key);
                    cd = new CellData();
                    cd.col = columnIndex + 1;
                    cd.row = rowIndex + 1;
                    cd.cellStyle = "" + cell.getCellStyle().getIndex();
                    updatedCellData.add(cd);
                }
            } else if (markedCells.contains(key)) {
                sentCells.add(key);
                updatedCellData.add(cd);
            }
        }
    }
    if (!changedFormulaCells.isEmpty()) {
        fireFormulaValueChangeEvent(changedFormulaCells);
        changedFormulaCells = new HashSet<CellReference>();
    }
    // empty cells have cell data with just col and row
    updatedCellData.addAll(removedCells);
    if (!updatedCellData.isEmpty()) {
        spreadsheet.getRpcProxy().cellsUpdated(updatedCellData);
        spreadsheet.getRpcProxy().refreshCellStyles();
    }
    markedCells.clear();
    removedCells.clear();
}

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

License:Open Source License

/**
 * Removes all the cells within the given bounds from the Spreadsheet and
 * the underlying POI model.// w w w  .ja v a 2s  .c  om
 *
 * @param firstRow
 *            Starting row index, 1-based
 * @param firstColumn
 *            Starting column index, 1-based
 * @param lastRow
 *            Ending row index, 1-based
 * @param lastColumn
 *            Ending column index, 1-based
 * @param clearRemovedCellStyle
 *            true to also clear styles from the removed cells
 */
protected void removeCells(int firstRow, int firstColumn, int lastRow, int lastColumn,
        boolean clearRemovedCellStyle) {
    final Workbook workbook = spreadsheet.getWorkbook();
    final Sheet activeSheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
    for (int i = firstRow - 1; i < lastRow; i++) {
        Row row = activeSheet.getRow(i);
        if (row != null) {
            for (int j = firstColumn - 1; j < lastColumn; j++) {
                Cell cell = row.getCell(j);
                if (cell != null) {
                    final String key = SpreadsheetUtil.toKey(j + 1, i + 1);
                    if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
                        sentFormulaCells.remove(key);
                    } else {
                        sentCells.remove(key);
                    }
                    if (cell.getHyperlink() != null) {
                        removeHyperlink(cell, activeSheet);
                    }
                    if (clearRemovedCellStyle) {
                        // update style to 0
                        cell.setCellStyle(null);
                        spreadsheet.getSpreadsheetStyleFactory().cellStyleUpdated(cell, true);
                    }
                    // need to make protection etc. settings for the cell
                    // won't get effected. deleting the cell would make it
                    // locked
                    if (clearRemovedCellStyle || cell.getCellStyle().getIndex() == 0) {
                        CellData cd = new CellData();
                        cd.col = j + 1;
                        cd.row = i + 1;
                        removedCells.add(cd);
                    } else {
                        markedCells.add(key);
                    }
                    cell.setCellValue((String) null);
                    getFormulaEvaluator().notifyUpdateCell(cell);
                }
            }
        }
    }
}

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

License:Open Source License

/**
 * Removes an individual cell from the Spreadsheet and the underlying POI
 * model./*from w w w .  j  av a  2s . co m*/
 *
 * @param rowIndex
 *            Row index of target cell, 1-based
 * @param colIndex
 *            Column index of target cell, 1-based
 * @param clearRemovedCellStyle
 *            true to also clear styles from the removed cell
 */
protected void removeCell(int rowIndex, int colIndex, boolean clearRemovedCellStyle) {
    final Workbook workbook = spreadsheet.getWorkbook();
    final Sheet activeSheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
    final Row row = activeSheet.getRow(rowIndex - 1);
    if (row != null) {
        final Cell cell = row.getCell(colIndex - 1);
        if (cell != null) {
            CellData cd = new CellData();
            cd.col = colIndex;
            cd.row = rowIndex;
            final String key = SpreadsheetUtil.toKey(colIndex, rowIndex);
            if (clearRemovedCellStyle || cell.getCellStyle().getIndex() == 0) {
                removedCells.add(cd);
            } else {
                markedCells.add(key);
            }
            if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
                sentFormulaCells.remove(key);
            } else {
                sentCells.remove(key);
            }
            // POI (3.9) doesn't have a method for removing a hyperlink !!!
            if (cell.getHyperlink() != null) {
                removeHyperlink(cell, activeSheet);
            }
            if (clearRemovedCellStyle) {
                // update style to 0
                cell.setCellStyle(null);
                spreadsheet.getSpreadsheetStyleFactory().cellStyleUpdated(cell, true);
            }
            cell.setCellValue((String) null);
            getFormulaEvaluator().notifyUpdateCell(cell);
        }
    }
}

From source file:com.vaadin.addon.spreadsheet.charts.converter.xssfreader.AbstractSeriesReader.java

private int calculateDecimalsForTooltip(List<CellReference> ptList) {

    if (ptList.size() <= 0) {
        // No points, so go with the default number of decimals
        return -1;
    }//www . j a v a 2  s  .  c o  m

    CellReference ref = ptList.get(0);
    Sheet sheet = spreadsheet.getWorkbook().getSheet(ref.getSheetName());
    Cell cell = spreadsheet.getCell(ref, sheet);
    if (cell == null) {
        return -1;
    }
    CellStyle style = cell.getCellStyle();
    String styleString = style.getDataFormatString();
    if (styleString == null || styleString.isEmpty() || styleString.equals("General")) {
        // No formatting info given, so go with the default number of
        // decimals
        return -1;
    }

    //In formatting strings "." is always used it seems.
    char sep = '.';

    // Take the last occurrence if the user has the same symbol as thousand
    // separator (should not be possible)
    int sepIndex = styleString.trim().lastIndexOf(sep);
    int decimalCount;
    if (sepIndex < 0) {
        decimalCount = 0;
    } else {
        decimalCount = styleString.length() - sepIndex - 1;
    }
    return decimalCount;
}