Example usage for org.apache.poi.ss.usermodel Workbook getSheetAt

List of usage examples for org.apache.poi.ss.usermodel Workbook getSheetAt

Introduction

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

Prototype

Sheet getSheetAt(int index);

Source Link

Document

Get the Sheet object at the given index.

Usage

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

License:Open Source License

private void shiftRowsUpInSelection(int newFirstRow) {
    CellRangeAddress paintedCellRange = spreadsheet.getCellSelectionManager().getSelectedCellRange();
    int r1 = paintedCellRange.getFirstRow() + 1;
    int r2 = paintedCellRange.getLastRow() + 1;
    int c1 = paintedCellRange.getFirstColumn() + 1;
    int c2 = paintedCellRange.getLastColumn() + 1;
    Workbook workbook = spreadsheet.getWorkbook();
    final Sheet activeSheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
    for (int shiftedRowIndex = r1; shiftedRowIndex <= r2; shiftedRowIndex++) {
        final Row shiftedRow = activeSheet.getRow(shiftedRowIndex - 1);
        int newRowIndex = r1 - 1 - (shiftedRowIndex - r1);
        while (newRowIndex >= newFirstRow) {
            if (shiftedRow != null) {
                Row newRow = activeSheet.getRow(newRowIndex - 1);
                if (newRow == null) {
                    newRow = activeSheet.createRow(newRowIndex - 1);
                }//from ww w . j av a 2 s .  co m
                for (int c = c1; c <= c2; c++) {
                    Double sequenceIncrement = getColumnSequenceIncrement(c, r1, r2);
                    Cell shiftedCell = shiftedRow.getCell(c - 1);
                    Cell newCell = newRow.getCell(c - 1);
                    if (shiftedCell != null) {
                        if (newCell == null) {
                            newCell = newRow.createCell(c - 1);
                        }
                        shiftCellValue(shiftedCell, newCell, false, sequenceIncrement);
                    } else if (newCell != null) {
                        // update style to 0
                        newCell.setCellStyle(null);
                        spreadsheet.getSpreadsheetStyleFactory().cellStyleUpdated(newCell, true);
                        newCell.setCellValue((String) null);
                        getCellValueManager().cellDeleted(newCell);
                    }
                }
            } else {
                getCellValueManager().removeCells(newRowIndex, c1, newRowIndex, c2, true);
            }
            newRowIndex = newRowIndex - (r2 - r1) - 1;
        }
    }
}

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

License:Open Source License

private void shiftColumnsRightInSelection(int newRightMostColumn) {
    CellRangeAddress paintedCellRange = spreadsheet.getCellSelectionManager().getSelectedCellRange();
    int r1 = paintedCellRange.getFirstRow() + 1;
    int r2 = paintedCellRange.getLastRow() + 1;
    int c1 = paintedCellRange.getFirstColumn() + 1;
    int c2 = paintedCellRange.getLastColumn() + 1;
    Workbook workbook = spreadsheet.getWorkbook();
    final Sheet activeSheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
    for (int rIndex = r1; rIndex <= r2; rIndex++) {
        final Row row = activeSheet.getRow(rIndex - 1);
        if (row != null) {
            Double sequenceIncrement = getRowSequenceIncrement(rIndex, c1, c2);
            for (int shiftedCellIndex = c1; shiftedCellIndex <= c2; shiftedCellIndex++) {
                Cell shiftedCell = row.getCell(shiftedCellIndex - 1);
                int newCellIndex = c2 + 1 + (shiftedCellIndex - c1);
                while (newCellIndex <= newRightMostColumn) {
                    Cell newCell = row.getCell(newCellIndex - 1);
                    if (shiftedCell != null) {
                        if (newCell == null) {
                            newCell = row.createCell(newCellIndex - 1);
                        }//from www.j  ava 2s  .c  om
                        shiftCellValue(shiftedCell, newCell, false, sequenceIncrement);

                    } else if (newCell != null) {
                        newCell.setCellValue((String) null);
                        getCellValueManager().cellDeleted(newCell);
                        // update style to 0
                        newCell.setCellStyle(null);
                        spreadsheet.getSpreadsheetStyleFactory().cellStyleUpdated(newCell, true);
                    }
                    newCellIndex += (c2 - c1) + 1;
                }
            }
        }
    }
}

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

License:Open Source License

private void shiftColumnsLeftInSelection(int newLeftMostColumn) {
    CellRangeAddress paintedCellRange = spreadsheet.getCellSelectionManager().getSelectedCellRange();
    int r1 = paintedCellRange.getFirstRow() + 1;
    int r2 = paintedCellRange.getLastRow() + 1;
    int c1 = paintedCellRange.getFirstColumn() + 1;
    int c2 = paintedCellRange.getLastColumn() + 1;
    Workbook workbook = spreadsheet.getWorkbook();
    final Sheet activeSheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
    for (int rIndex = r1; rIndex <= r2; rIndex++) {
        final Row row = activeSheet.getRow(rIndex - 1);
        if (row != null) {
            Double sequenceIncrement = getRowSequenceIncrement(rIndex, c1, c2);
            for (int shiftedCellIndex = c1; shiftedCellIndex <= c2; shiftedCellIndex++) {
                Cell shiftedCell = row.getCell(shiftedCellIndex - 1);
                int newCellIndex = c1 - (shiftedCellIndex - c1) - 1;
                while (newCellIndex >= newLeftMostColumn) {
                    Cell newCell = row.getCell(newCellIndex - 1);
                    if (shiftedCell != null) {
                        if (newCell == null) {
                            newCell = row.createCell(newCellIndex - 1);
                        }//  w ww  . j  a v a 2 s.  c o m
                        shiftCellValue(shiftedCell, newCell, false, sequenceIncrement);
                    } else if (newCell != null) {
                        newCell.setCellValue((String) null);
                        getCellValueManager().cellDeleted(newCell);
                        // update style to 0
                        newCell.setCellStyle(null);
                        spreadsheet.getSpreadsheetStyleFactory().cellStyleUpdated(newCell, true);
                    }
                    newCellIndex = newCellIndex - (c2 - c1) - 1;
                }
            }
        }
    }
}

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

License:Open Source License

/**
 * Returns the increment between all consecutive cells in row with rIndex
 * from column c1 to column c2/*w w  w.  j a  va  2  s  .  c  om*/
 * 
 * @param rIndex
 *            Row index for the sequence recognition, 1-based
 * @param c1
 *            First column of the row to be considered, 1-based
 * @param c2
 *            Last column of the row to be considered, 1-based
 * @return common difference or null
 */
private Double getRowSequenceIncrement(int rIndex, int c1, int c2) {
    Double result = null;
    Workbook workbook = spreadsheet.getWorkbook();
    final Sheet activeSheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
    final Row row = activeSheet.getRow(rIndex - 1);
    if (row != null) {
        Cell firstCell = row.getCell(c1 - 1);
        if (firstCell != null) {
            if (firstCell.getCellType() == CELL_TYPE_STRING) {
                return getSequenceIncrement(getRowStringValues(row, c1, c2));
            } else if (firstCell.getCellType() == CELL_TYPE_NUMERIC) {
                return getSequenceIncrement(getRowNumericValues(row, c1, c2));
            }
        }
    }
    return result;
}

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

License:Open Source License

/**
 * Returns the increment between all consecutive cells in column with cIndex
 * from row r1 to row r2//  ww  w.j  a va  2  s.c o  m
 * 
 * @param cIndex
 *            Column index for the sequence recognition, 1-based
 * 
 * @param r1
 *            First row of the column to be considered, 1-based
 * @param r2
 *            Last row of the column to be considered, 1-based
 * @return common difference or null
 */
private Double getColumnSequenceIncrement(int cIndex, int r1, int r2) {
    Double result = null;
    Workbook workbook = spreadsheet.getWorkbook();
    final Sheet activeSheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
    final Row row = activeSheet.getRow(r1 - 1);
    if (row != null) {
        Cell firstCell = row.getCell(cIndex - 1);
        if (firstCell != null) {
            if (firstCell.getCellType() == CELL_TYPE_STRING) {
                return getSequenceIncrement(getColumnStringValues(activeSheet, cIndex, r1, r2));
            } else if (firstCell.getCellType() == CELL_TYPE_NUMERIC) {
                return getSequenceIncrement(getColumnNumericValues(activeSheet, cIndex, r1, r2));
            }
        }
    }
    return result;
}

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 w  w. ja  va 2  s.com
 *
 * 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

/**
 * Checks whether the default deletion handling should be performed for the
 * selected cell or whether a custom deletion handler takes care of
 * everything./*from   w  w  w.ja va  2 s. com*/
 * 
 * @param selectedCellReference
 * @return {@code true} if the default handling should be performed,
 *         {@code false} otherwise
 */
private boolean passesDeletionCheck(CellReference selectedCellReference) {
    if (selectedCellReference == null || customCellDeletionHandler == null) {
        return true;
    }
    final Workbook workbook = spreadsheet.getWorkbook();
    final Sheet activeSheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
    int rowIndex = selectedCellReference.getRow();
    final Row row = activeSheet.getRow(rowIndex);
    if (row != null) {
        short colIndex = selectedCellReference.getCol();
        final Cell cell = row.getCell(colIndex);
        if (cell != null) {
            return customCellDeletionHandler.cellDeleted(cell, activeSheet, colIndex, rowIndex,
                    getFormulaEvaluator(), formatter);
        }
    }
    return true;
}

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

License:Open Source License

/**
 * Checks whether the default deletion handling should be performed for the
 * individually selected cells or whether a custom deletion handler takes
 * care of everything./*from  www .ja  v a2s . c o  m*/
 * 
 * @param individualSelectedCells
 * @return {@code true} if the default handling should be performed,
 *         {@code false} otherwise
 */
private boolean passesDeletionCheck(List<CellReference> individualSelectedCells) {
    if (individualSelectedCells.isEmpty() || customCellDeletionHandler == null) {
        return true;
    }
    final Workbook workbook = spreadsheet.getWorkbook();
    final Sheet activeSheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
    return customCellDeletionHandler.individualSelectedCellsDeleted(individualSelectedCells, activeSheet,
            getFormulaEvaluator(), formatter);
}

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

License:Open Source License

/**
 * Checks whether the default deletion handling should be performed for the
 * cell range or whether a custom deletion handler takes care of everything.
 * /*from   w ww  .jav a 2 s  . c  o m*/
 * @param cellRangeAddresses
 * @return {@code true} if the default handling should be performed,
 *         {@code false} otherwise
 */
private boolean passesRangeDeletionCheck(List<CellRangeAddress> cellRangeAddresses) {
    if (cellRangeAddresses.isEmpty() || customCellDeletionHandler == null) {
        return true;
    }
    final Workbook workbook = spreadsheet.getWorkbook();
    final Sheet activeSheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
    return customCellDeletionHandler.cellRangeDeleted(cellRangeAddresses, activeSheet, getFormulaEvaluator(),
            formatter);
}

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

License:Open Source License

/**
 * Gets cell data for cells within the given bounds.
 *
 * @param firstRow/*w  w  w .  jav  a2s.c om*/
 *            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
 * @return A list of CellData for the cells in the given area.
 */
protected ArrayList<CellData> loadCellDataForRowAndColumnRange(int firstRow, int firstColumn, int lastRow,
        int lastColumn) {
    ArrayList<CellData> cellData = new ArrayList<CellData>();
    Workbook workbook = spreadsheet.getWorkbook();
    final Sheet activeSheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
    Map<String, String> componentIDtoCellKeysMap = spreadsheet.getState(false).componentIDtoCellKeysMap;
    @SuppressWarnings("unchecked")
    final Collection<String> customComponentCells = (Collection<String>) (componentIDtoCellKeysMap == null
            ? Collections.emptyList()
            : componentIDtoCellKeysMap.values());
    for (int r = firstRow - 1; r < lastRow; r++) {
        Row row = activeSheet.getRow(r);
        if (row != null && row.getLastCellNum() != -1 && row.getLastCellNum() >= firstColumn) {
            for (int c = firstColumn - 1; c < lastColumn; c++) {
                final String key = SpreadsheetUtil.toKey(c + 1, r + 1);
                if (!customComponentCells.contains(key) && !sentCells.contains(key)
                        && !sentFormulaCells.contains(key)) {
                    Cell cell = row.getCell(c);
                    if (cell != null) {
                        final CellData cd = createCellDataForCell(cell);
                        if (cd != null) {
                            int cellType = cell.getCellType();
                            if (cellType == Cell.CELL_TYPE_FORMULA) {
                                sentFormulaCells.add(key);
                            } else {
                                sentCells.add(key);
                            }
                            cellData.add(cd);
                        }
                    }
                }
            }
        }
    }
    return cellData;
}