List of usage examples for org.apache.poi.ss.usermodel Cell getCellFormula
String getCellFormula();
SUM(C4:E4)
From source file:com.vaadin.addon.spreadsheet.CellSelectionManager.java
License:Open Source License
/** * Reports the selected cell formula value, if any. This method is called * when the cell value has changed via sheet cell selection change. * // www . j a va 2 s . c o m * This method can also be used when the selected cell has NOT changed but * the value it displays on the formula field might have changed and needs * to be updated. * * @param rowIndex * 1-based * @param columnIndex * 1-based */ private void handleCellSelection(int rowIndex, int columnIndex) { Workbook workbook = spreadsheet.getWorkbook(); final Row row = workbook.getSheetAt(workbook.getActiveSheetIndex()).getRow(rowIndex - 1); if (row != null) { final Cell cell = row.getCell(columnIndex - 1); if (cell != null) { String value = ""; boolean formula = cell.getCellType() == Cell.CELL_TYPE_FORMULA; if (!spreadsheet.isCellHidden(cell)) { if (formula) { value = cell.getCellFormula(); } else { value = spreadsheet.getCellValue(cell); } } spreadsheet.getRpcProxy().showCellValue(value, columnIndex, rowIndex, formula, spreadsheet.isCellLocked(cell)); } else { spreadsheet.getRpcProxy().showCellValue("", columnIndex, rowIndex, false, spreadsheet.isCellLocked(cell)); } } else { spreadsheet.getRpcProxy().showCellValue("", columnIndex, rowIndex, false, spreadsheet.isActiveSheetProtected()); } }
From source file:com.vaadin.addon.spreadsheet.CellSelectionManager.java
License:Open Source License
/** * Handles the new cell range that was given in the address field, returns * the range and new selected cell formula/value (if any) * /*w ww. j a va2 s. co m*/ * @param cra * Range of cells to select */ protected void handleCellRangeSelection(CellRangeAddress cra) { int row1 = cra.getFirstRow(); int row2 = cra.getLastRow(); int col1 = cra.getFirstColumn(); int col2 = cra.getLastColumn(); Workbook workbook = spreadsheet.getWorkbook(); final Row row = workbook.getSheetAt(workbook.getActiveSheetIndex()).getRow(row1); if (row != null) { final Cell cell = row.getCell(col1); if (cell != null) { String value = ""; boolean formula = cell.getCellType() == Cell.CELL_TYPE_FORMULA; if (!spreadsheet.isCellHidden(cell)) { if (formula) { value = cell.getCellFormula(); } else { value = spreadsheet.getCellValue(cell); } } spreadsheet.getRpcProxy().showSelectedCellRange(col1 + 1, col2 + 1, row1 + 1, row2 + 1, value, formula, spreadsheet.isCellLocked(cell)); } else { spreadsheet.getRpcProxy().showSelectedCellRange(col1 + 1, col2 + 1, row1 + 1, row2 + 1, "", false, spreadsheet.isCellLocked(cell)); } } else { spreadsheet.getRpcProxy().showSelectedCellRange(col1 + 1, col2 + 1, row1 + 1, row2 + 1, "", false, spreadsheet.isActiveSheetProtected()); } }
From source file:com.vaadin.addon.spreadsheet.CellSelectionManager.java
License:Open Source License
/** * Sets the given range and starting point as the current selection. * /*from w ww . j a va2 s . co m*/ * @param startingPoint * Reference to starting point * @param cellsToSelect * Selection area */ protected void handleCellRangeSelection(CellReference startingPoint, CellRangeAddress cellsToSelect, boolean scroll) { int row1 = cellsToSelect.getFirstRow(); int row2 = cellsToSelect.getLastRow(); int col1 = cellsToSelect.getFirstColumn(); int col2 = cellsToSelect.getLastColumn(); Workbook workbook = spreadsheet.getWorkbook(); final Row row = workbook.getSheetAt(workbook.getActiveSheetIndex()).getRow(startingPoint.getRow()); if (row != null) { final Cell cell = row.getCell(startingPoint.getCol()); if (cell != null) { String value = ""; boolean formula = cell.getCellType() == Cell.CELL_TYPE_FORMULA; if (!spreadsheet.isCellHidden(cell)) { if (formula) { value = cell.getCellFormula(); } else { value = spreadsheet.getCellValue(cell); } } spreadsheet.getRpcProxy().setSelectedCellAndRange(startingPoint.getCol() + 1, startingPoint.getRow() + 1, col1 + 1, col2 + 1, row1 + 1, row2 + 1, value, formula, spreadsheet.isCellLocked(cell), scroll); } else { spreadsheet.getRpcProxy().setSelectedCellAndRange(startingPoint.getCol() + 1, startingPoint.getRow() + 1, col1 + 1, col2 + 1, row1 + 1, row2 + 1, "", false, spreadsheet.isCellLocked(cell), scroll); } } else { spreadsheet.getRpcProxy().setSelectedCellAndRange(startingPoint.getCol() + 1, startingPoint.getRow() + 1, col1 + 1, col2 + 1, row1 + 1, row2 + 1, "", false, spreadsheet.isActiveSheetProtected(), scroll); } selectedCellReference = startingPoint; cellRangeAddresses.clear(); individualSelectedCells.clear(); paintedCellRange = cellsToSelect; if (col1 != col2 || row1 != row2) { cellRangeAddresses.add(cellsToSelect); } ensureClientHasSelectionData(); fireNewSelectionChangeEvent(); }
From source file:com.vaadin.addon.spreadsheet.CellSelectionShifter.java
License:Open Source License
/** * Set's cell value for the newCell. It will be the same as shiftedCell with * updated references./*from w w w . j a v a2s . com*/ * * @param shiftedCell * Source cell * @param newCell * Resulting new cell */ private void shiftFormula(Cell shiftedCell, Cell newCell) { try { if (shiftedCell.getColumnIndex() != newCell.getColumnIndex()) { // shift column indexes int collDiff = newCell.getColumnIndex() - shiftedCell.getColumnIndex(); Matcher matcher = rowShiftPattern.matcher(shiftedCell.getCellFormula()); String originalFormula = shiftedCell.getCellFormula(); StringBuilder newFormula = new StringBuilder(); int lastEnd = 0; while (matcher.find()) { String s = matcher.group(); String replacement; if (!s.startsWith("$")) { String oldIndexString = s.replaceAll("[$]{0,1}\\d+", ""); int columnIndex = SpreadsheetUtil.getColHeaderIndex(oldIndexString); columnIndex += collDiff; replacement = s.replace(oldIndexString, SpreadsheetUtil.getColHeader(columnIndex)); } else { // if column has a '$' reference shouldn't change replacement = s; } newFormula.append(originalFormula.substring(lastEnd, matcher.start())); newFormula.append(replacement); lastEnd = matcher.end(); } newFormula.append(originalFormula.substring(lastEnd)); newCell.setCellFormula(newFormula.toString()); } else { // shift row indexes int rowDiff = newCell.getRowIndex() - shiftedCell.getRowIndex(); Matcher matcher = rowShiftPattern.matcher(shiftedCell.getCellFormula()); String originalFormula = shiftedCell.getCellFormula(); StringBuilder newFormula = new StringBuilder(); int lastEnd = 0; while (matcher.find()) { String s = matcher.group(); String rowString = s.replaceAll("[$]{0,1}[a-zA-Z]+", ""); String replacement; if (!rowString.startsWith("$")) { int row = Integer.parseInt(rowString); row += rowDiff; replacement = s.replace(rowString, Integer.toString(row)); } else { // if row has a '$' reference shouldn't change replacement = s; } newFormula.append(originalFormula.substring(lastEnd, matcher.start())); newFormula.append(replacement); lastEnd = matcher.end(); } newFormula.append(originalFormula.substring(lastEnd)); newCell.setCellFormula(newFormula.toString()); } } catch (Exception e) { LOGGER.log(Level.FINE, e.getMessage(), e); // TODO visualize shifting error newCell.setCellFormula(shiftedCell.getCellFormula()); } spreadsheet.getCellValueManager().getFormulaEvaluator().notifySetFormula(newCell); }
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 w w . ja v a 2 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
public String getOriginalCellValue(Cell cell) { if (cell == null) { return ""; }//from w w w . j a va 2s. c o m int cellType = cell.getCellType(); switch (cellType) { case Cell.CELL_TYPE_FORMULA: return cell.getCellFormula(); case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { Date dateCellValue = cell.getDateCellValue(); if (dateCellValue != null) { return new SimpleDateFormat().format(dateCellValue); } return ""; } return originalValueDecimalFormat.format(cell.getNumericCellValue()); case Cell.CELL_TYPE_STRING: return cell.getStringCellValue(); case Cell.CELL_TYPE_BOOLEAN: return String.valueOf(cell.getBooleanCellValue()); case Cell.CELL_TYPE_BLANK: return ""; case Cell.CELL_TYPE_ERROR: return String.valueOf(cell.getErrorCellValue()); } return ""; }
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./*from w w w. ja va 2s . c o m*/ * * 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.command.CellValueCommand.java
License:Open Source License
/** * Returns the current value of the given Cell * // w w w .j a v a 2s. c o m * @param cell * Target cell * @return Current value of the cell or null if not available */ protected Object getCellValue(Cell cell) { if (cell == null) { return null; } else { switch (cell.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: return cell.getBooleanCellValue(); case Cell.CELL_TYPE_ERROR: return cell.getErrorCellValue(); case Cell.CELL_TYPE_FORMULA: return "=" + cell.getCellFormula(); case Cell.CELL_TYPE_NUMERIC: return cell.getNumericCellValue(); case Cell.CELL_TYPE_STRING: return cell.getStringCellValue(); default: return null; } } }
From source file:com.vaadin.addon.spreadsheet.DefaultHyperlinkCellClickHandler.java
License:Open Source License
/** * Should only be called for cells {@link #isHyperlinkFormulaCell(Cell)} * returns true.//from ww w .j a va 2 s . com * <p> * The address is inside the first quotation marks: * <code>HYPERLINK("address","friendly name")</code> * * @param cell * Target cell containing a hyperlink function * @return the address that the hyperlink function points to */ public final static String getHyperlinkFunctionCellAddress(Cell cell) { String cellFormula = cell.getCellFormula(); int startindex = cellFormula.indexOf("\""); int endindex = cellFormula.indexOf('"', startindex + 1); String address = cellFormula.substring(startindex + 1, endindex); return address; }
From source file:com.vaadin.addon.spreadsheet.DefaultHyperlinkCellClickHandler.java
License:Open Source License
/** * Returns true if the cell contains a hyperlink function. * /*from w w w . ja v a 2 s. c o m*/ * @param cell * Cell to investigate * @return True if hyperlink is found */ public final static boolean isHyperlinkFormulaCell(Cell cell) { return cell != null && cell.getCellType() == Cell.CELL_TYPE_FORMULA && cell.getCellFormula().startsWith("HYPERLINK("); }