Example usage for org.apache.poi.ss.usermodel Row getHeightInPoints

List of usage examples for org.apache.poi.ss.usermodel Row getHeightInPoints

Introduction

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

Prototype

float getHeightInPoints();

Source Link

Document

Returns row height measured in point size.

Usage

From source file:com.actelion.research.spiritapp.ui.util.PDFUtils.java

License:Open Source License

public static void convertHSSF2Pdf(Workbook wb, String header, File reportFile) throws Exception {
    assert wb != null;
    assert reportFile != null;

    //Precompute formula
    FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        Sheet sheet = wb.getSheetAt(i);//from  www  .  j av a  2s .  co  m

        for (Row r : sheet) {
            for (Cell c : r) {
                if (c.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
                    try {
                        evaluator.evaluateFormulaCell(c);
                    } catch (Exception e) {
                        System.err.println(e);
                    }
                }
            }
        }
    }

    File tmp = File.createTempFile("tmp_", ".xlsx");
    try (OutputStream out = new BufferedOutputStream(new FileOutputStream(tmp))) {
        wb.write(out);
    }

    //Find page orientation
    int maxColumnsGlobal = 0;
    for (int sheetNo = 0; sheetNo < wb.getNumberOfSheets(); sheetNo++) {
        Sheet sheet = wb.getSheetAt(sheetNo);
        for (Iterator<Row> rowIterator = sheet.iterator(); rowIterator.hasNext();) {
            Row row = rowIterator.next();
            maxColumnsGlobal = Math.max(maxColumnsGlobal, row.getLastCellNum());
        }
    }

    Rectangle pageSize = maxColumnsGlobal < 10 ? PageSize.A4 : PageSize.A4.rotate();
    Document pdfDocument = new Document(pageSize, 10f, 10f, 20f, 20f);

    PdfWriter writer = PdfWriter.getInstance(pdfDocument, new FileOutputStream(reportFile));
    addHeader(writer, header);
    pdfDocument.open();
    //we have two columns in the Excel sheet, so we create a PDF table with two columns
    //Note: There are ways to make this dynamic in nature, if you want to.
    //Loop through sheets
    for (int sheetNo = 0; sheetNo < wb.getNumberOfSheets(); sheetNo++) {
        Sheet sheet = wb.getSheetAt(sheetNo);

        //Loop through rows, to find number of columns
        int minColumns = 1000;
        int maxColumns = 0;
        for (Iterator<Row> rowIterator = sheet.iterator(); rowIterator.hasNext();) {
            Row row = rowIterator.next();
            if (row.getFirstCellNum() >= 0)
                minColumns = Math.min(minColumns, row.getFirstCellNum());
            if (row.getLastCellNum() >= 0)
                maxColumns = Math.max(maxColumns, row.getLastCellNum());
        }
        if (maxColumns == 0)
            continue;

        //Loop through first rows, to find relative width
        float[] widths = new float[maxColumns];
        int totalWidth = 0;
        for (int c = 0; c < maxColumns; c++) {
            int w = sheet.getColumnWidth(c);
            widths[c] = w;
            totalWidth += w;
        }

        for (int c = 0; c < maxColumns; c++) {
            widths[c] /= totalWidth;
        }

        //Create new page and a new chapter with the sheet's name
        if (sheetNo > 0)
            pdfDocument.newPage();
        Chapter pdfSheet = new Chapter(sheet.getSheetName(), sheetNo + 1);

        PdfPTable pdfTable = null;
        PdfPCell pdfCell = null;
        boolean inTable = false;

        //Loop through cells, to create the content
        //         boolean leftBorder = true;
        //         boolean[] topBorder = new boolean[maxColumns+1];
        for (int r = 0; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);

            //Check if we exited a table (empty line)
            if (row == null) {
                if (pdfTable != null) {
                    addTable(pdfDocument, pdfSheet, totalWidth, widths, pdfTable);
                    pdfTable = null;
                }
                inTable = false;
                continue;
            }

            //Check if we start a table (>MIN_COL_IN_TABLE columns)
            if (row.getLastCellNum() >= MIN_COL_IN_TABLE) {
                inTable = true;
            }

            if (!inTable) {
                //Process the data outside table, just add the text
                boolean hasData = false;
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    if (cell.getCellType() == Cell.CELL_TYPE_BLANK)
                        continue;
                    Chunk chunk = getChunk(wb, cell);
                    pdfSheet.add(chunk);
                    pdfSheet.add(new Chunk(" "));
                    hasData = true;
                }
                if (hasData)
                    pdfSheet.add(Chunk.NEWLINE);

            } else {
                //Process the data in table
                if (pdfTable == null) {
                    //Create table
                    pdfTable = new PdfPTable(maxColumns);
                    pdfTable.setWidths(widths);
                    //                  topBorder = new boolean[maxColumns+1];
                }

                int cellNumber = minColumns;
                //               leftBorder = false;
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {

                    Cell cell = cellIterator.next();

                    for (; cellNumber < cell.getColumnIndex(); cellNumber++) {
                        pdfCell = new PdfPCell();
                        pdfCell.setBorder(0);
                        pdfTable.addCell(pdfCell);
                    }

                    Chunk phrase = getChunk(wb, cell);
                    pdfCell = new PdfPCell(new Phrase(phrase));
                    pdfCell.setFixedHeight(row.getHeightInPoints() - 3);
                    pdfCell.setNoWrap(!cell.getCellStyle().getWrapText());
                    pdfCell.setPaddingLeft(1);
                    pdfCell.setHorizontalAlignment(
                            cell.getCellStyle().getAlignment() == CellStyle.ALIGN_CENTER ? PdfPCell.ALIGN_CENTER
                                    : cell.getCellStyle().getAlignment() == CellStyle.ALIGN_RIGHT
                                            ? PdfPCell.ALIGN_RIGHT
                                            : PdfPCell.ALIGN_LEFT);
                    pdfCell.setUseBorderPadding(false);
                    pdfCell.setUseVariableBorders(false);
                    pdfCell.setBorderWidthRight(cell.getCellStyle().getBorderRight() == 0 ? 0 : .5f);
                    pdfCell.setBorderWidthBottom(cell.getCellStyle().getBorderBottom() == 0 ? 0
                            : cell.getCellStyle().getBorderBottom() > 1 ? 1 : .5f);
                    pdfCell.setBorderWidthLeft(cell.getCellStyle().getBorderLeft() == 0 ? 0
                            : cell.getCellStyle().getBorderLeft() > 1 ? 1 : .5f);
                    pdfCell.setBorderWidthTop(cell.getCellStyle().getBorderTop() == 0 ? 0
                            : cell.getCellStyle().getBorderTop() > 1 ? 1 : .5f);
                    String color = cell.getCellStyle().getFillForegroundColorColor() == null ? null
                            : ((XSSFColor) cell.getCellStyle().getFillForegroundColorColor()).getARGBHex();
                    if (color != null)
                        pdfCell.setBackgroundColor(new Color(Integer.decode("0x" + color.substring(2))));
                    pdfTable.addCell(pdfCell);
                    cellNumber++;
                }
                for (; cellNumber < maxColumns; cellNumber++) {
                    pdfCell = new PdfPCell();
                    pdfCell.setBorder(0);
                    pdfTable.addCell(pdfCell);
                }
            }

            //Custom code to add all images on the first sheet (works for reporting)
            if (sheetNo == 0 && row.getRowNum() == 0) {
                for (PictureData pd : wb.getAllPictures()) {
                    try {
                        Image pdfImg = Image.getInstance(pd.getData());
                        pdfImg.scaleToFit(
                                pageSize.getWidth() * .8f - pageSize.getBorderWidthLeft()
                                        - pageSize.getBorderWidthRight(),
                                pageSize.getHeight() * .8f - pageSize.getBorderWidthTop()
                                        - pageSize.getBorderWidthBottom());
                        pdfSheet.add(pdfImg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if (pdfTable != null) {
            addTable(pdfDocument, pdfSheet, totalWidth, widths, pdfTable);
        }

        pdfDocument.add(pdfSheet);
    }
    pdfDocument.close();

}

From source file:com.github.crab2died.handler.SheetTemplateHandler.java

License:Open Source License

/**
 * ???/*from  ww w.ja  va  2  s  . c o m*/
 */
private static void initModuleConfig(SheetTemplate template) {

    for (Row row : template.sheet) {
        for (Cell c : row) {
            if (c.getCellTypeEnum() != CellType.STRING)
                continue;
            String str = c.getStringCellValue().trim().toLowerCase();
            // ??
            if (HandlerConstant.SERIAL_NUMBER.equals(str)) {
                template.serialNumberColumnIndex = c.getColumnIndex();
            }
            // ?
            if (HandlerConstant.DATA_INIT_INDEX.equals(str)) {
                template.initColumnIndex = c.getColumnIndex();
                template.initRowIndex = row.getRowNum();
                template.rowHeight = row.getHeightInPoints();
            }
            // ???
            initStyles(template, c, str);
        }
    }
}

From source file:com.upbest.utils.AddDimensionedImage.java

License:Apache License

/**
 * Determines whether the sheets row should be re-sized to accomodate
 * the image, adjusts the rows height if necessary and creates then
 * returns a ClientAnchorDetail object that facilitates construction of
 * a ClientAnchor that will fix the image on the sheet and establish
 * it's size./*from www.jav a  2 s.c o m*/
 *
 * @param sheet A reference to the sheet that will 'contain' the image.
 * @param rowNumber A primitive int that contains the index number of a
 *                  row on the sheet.
 * @param reqImageHeightMM A primitive double that contains the required
 *                         height of the image in millimetres
 * @param resizeBehaviour A primitive int whose value will indicate how the
 *                        height of the row should be adjusted if the
 *                        required height of the image is greater than the
 *                        height of the row.
 * @return An instance of the ClientAnchorDetail class that will contain
 *         the index number of the row containing the cell whose top
 *         left hand corner also defines the top left hand corner of the
 *         image, the index number of the row containing the cell whose
 *         top left hand corner also defines the bottom right hand
 *         corner of the image and an inset that determines how far the
 *         bottom edge of the image can protrude into the next (lower)
 *         row - expressed as a specific number of coordinate positions.
 */
private ClientAnchorDetail fitImageToRows(Sheet sheet, int rowNumber, double reqImageHeightMM,
        int resizeBehaviour) {
    Row row = null;
    double rowHeightMM = 0.0D;
    double rowCoordinatesPerMM = 0.0D;
    int pictureHeightCoordinates = 0;
    ClientAnchorDetail rowClientAnchorDetail = null;

    // Get the row and it's height
    row = sheet.getRow(rowNumber);
    if (row == null) {
        // Create row if it does not exist.
        row = sheet.createRow(rowNumber);
    }

    // Get the row's height in millimetres
    rowHeightMM = row.getHeightInPoints() / ConvertImageUnits.POINTS_PER_MILLIMETRE;

    // Check that the row's height will accomodate the image at the required
    // dimensions. If the height of the row is LESS than the required height
    // of the image, decide how the application should respond - resize the
    // row or overlay the image across a series of rows.
    if (rowHeightMM < reqImageHeightMM) {
        if ((resizeBehaviour == AddDimensionedImage.EXPAND_ROW)
                || (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) {
            row.setHeightInPoints((float) (reqImageHeightMM * ConvertImageUnits.POINTS_PER_MILLIMETRE));
            if (sheet instanceof HSSFSheet) {
                rowHeightMM = reqImageHeightMM;
                rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / rowHeightMM;
                pictureHeightCoordinates = (int) (reqImageHeightMM * rowCoordinatesPerMM);
            } else {
                pictureHeightCoordinates = (int) (reqImageHeightMM * AddDimensionedImage.EMU_PER_MM);
            }
            rowClientAnchorDetail = new ClientAnchorDetail(rowNumber, rowNumber, pictureHeightCoordinates);
        }
        // If the user has chosen to overlay both rows and columns or just
        // to expand ONLY the size of the columns, then calculate how to lay
        // the image out ver one or more rows.
        else if ((resizeBehaviour == AddDimensionedImage.OVERLAY_ROW_AND_COLUMN)
                || (resizeBehaviour == AddDimensionedImage.EXPAND_COLUMN)) {
            rowClientAnchorDetail = this.calculateRowLocation(sheet, rowNumber, reqImageHeightMM);
        }
    }
    // Else, if the image is smaller than the space available
    else {
        if (sheet instanceof HSSFSheet) {
            rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / rowHeightMM;
            pictureHeightCoordinates = (int) (reqImageHeightMM * rowCoordinatesPerMM);
        } else {
            pictureHeightCoordinates = (int) (reqImageHeightMM * AddDimensionedImage.EMU_PER_MM);
        }
        rowClientAnchorDetail = new ClientAnchorDetail(rowNumber, rowNumber, pictureHeightCoordinates);
    }
    return (rowClientAnchorDetail);
}

From source file:com.upbest.utils.AddDimensionedImage.java

License:Apache License

/**
 * If the image is to overlie more than one rows, calculations need to be
 * performed to determine how many rows and whether the image will
 * overlie just a part of one row in order to be presented at the
 * required size./*from  w ww.  ja  v  a  2  s  . c  o m*/
 *
 * @param sheet The sheet that will 'contain' the image.
 * @param startingRow A primitive int whose value is the index of the row
 *                    that contains the cell whose top left hand corner
 *                    should be aligned with the top left hand corner of
 *                    the image.
 * @param reqImageHeightMM A primitive double whose value will indicate the
 *                         required height of the image in millimetres.
 * @return An instance of the ClientAnchorDetail class that will contain
 *         the index number of the row containing the cell whose top
 *         left hand corner also defines the top left hand corner of the
 *         image, the index number of the row containing the cell whose top
 *         left hand corner also defines the bottom right hand corner of
 *         the image and an inset that determines how far the bottom edge
 *         can protrude into the next (lower) row - expressed as a specific
 *         number of co-ordinate positions.
 */
private ClientAnchorDetail calculateRowLocation(Sheet sheet, int startingRow, double reqImageHeightMM) {
    ClientAnchorDetail clientAnchorDetail = null;
    Row row = null;
    double rowHeightMM = 0.0D;
    double totalRowHeightMM = 0.0D;
    double overlapMM = 0.0D;
    double rowCoordinatesPerMM = 0.0D;
    int toRow = startingRow;
    int inset = 0;

    // Step through the rows in the sheet and accumulate a total of their
    // heights.
    while (totalRowHeightMM < reqImageHeightMM) {
        row = sheet.getRow(toRow);
        // Note, if the row does not already exist on the sheet then create
        // it here.
        if (row == null) {
            row = sheet.createRow(toRow);
        }
        // Get the row's height in millimetres and add to the running total.
        rowHeightMM = row.getHeightInPoints() / ConvertImageUnits.POINTS_PER_MILLIMETRE;
        totalRowHeightMM += rowHeightMM;
        toRow++;
    }
    // Owing to the way the loop above works, the rowNumber will have been
    // incremented one row too far. Undo that here.
    toRow--;
    // Check to see whether the image should occupy an exact number of
    // rows. If so, build the ClientAnchorDetail record to point
    // to those rows and with an inset of the total number of co-ordinate
    // position in the row.
    //
    // To overcome problems that can occur with comparing double values for
    // equality, cast both to int(s) to truncate the value; VERY crude and
    // I do not really like it!!
    if ((int) totalRowHeightMM == (int) reqImageHeightMM) {
        if (sheet instanceof HSSFSheet) {
            clientAnchorDetail = new ClientAnchorDetail(startingRow, toRow,
                    ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS);
        } else {
            clientAnchorDetail = new ClientAnchorDetail(startingRow, toRow,
                    (int) reqImageHeightMM * AddDimensionedImage.EMU_PER_MM);
        }
    } else {
        // Calculate how far the image will project into the next row. Note
        // that the height of the last row assessed is subtracted from the
        // total height of all rows assessed so far.
        overlapMM = reqImageHeightMM - (totalRowHeightMM - rowHeightMM);

        // To prevent an exception being thrown when the required width of
        // the image is very close indeed to the column size.
        if (overlapMM < 0) {
            overlapMM = 0.0D;
        }

        if (sheet instanceof HSSFSheet) {
            rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / rowHeightMM;
            inset = (int) (overlapMM * rowCoordinatesPerMM);
        } else {
            inset = (int) overlapMM * AddDimensionedImage.EMU_PER_MM;
        }
        clientAnchorDetail = new ClientAnchorDetail(startingRow, toRow, inset);
    }
    return (clientAnchorDetail);
}

From source file:com.vaadin.addon.spreadsheet.command.RowData.java

public void copy(int rowIndex) {
    isCopied = true;/*w w w . j  a  va 2 s . c om*/
    this.rowIndex = rowIndex;
    this.maxCol = spreadsheet.getLastColumn();
    cellsData.clear();
    mergedCells.clear();
    commentsWithoutCell.clear();

    Row row = spreadsheet.getActiveSheet().getRow(rowIndex);

    height = row == null ? null : row.getZeroHeight() ? 0.0F : row.getHeightInPoints();

    if (row != null) {
        copyCellsData(row);
    }

    Sheet sheet = spreadsheet.getActiveSheet();
    for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
        CellRangeAddress mergedRegion = sheet.getMergedRegion(i);
        if (mergedRegion.getFirstRow() == rowIndex) {
            mergedCells.add(mergedRegion);
        }
    }

}

From source file:com.vaadin.addon.spreadsheet.command.SizeChangeCommand.java

License:Open Source License

/**
 * Returns the current height/width of the target row/column.
 * //from   w w  w  . j a va 2  s . c o m
 * @param index
 *            row/column index, 0-based
 * @return current height for row OR width for column
 */
private Object getCurrentValue(int index) {
    if (type == Type.COLUMN) {
        if (getSheet().isColumnHidden(index)) {
            return 0;
        } else {
            return ExcelToHtmlUtils.getColumnWidthInPx(getSheet().getColumnWidth(index));
        }
    } else if (type == Type.ROW) {
        Row row = getSheet().getRow(index);
        // null rows use default row height
        // null height marks default height
        return row == null ? null : row.getZeroHeight() ? 0.0F : row.getHeightInPoints();
    }
    return null;
}

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

License:Open Source License

/**
 * Shifts rows between startRow and endRow n number of rows. If you use a
 * negative number for n, the rows will be shifted upwards. This method
 * ensures that rows can't wrap around.//from w ww. jav a 2  s  .c  o  m
 * <p>
 * If you are adding / deleting rows, you might want to change the number of
 * visible rows rendered {@link #getRows()} with {@link #setMaxRows(int)}.
 * <p>
 * See {@link Sheet#shiftRows(int, int, int, boolean, boolean)}.
 * 
 * @param startRow
 *            The first row to shift, 0-based
 * @param endRow
 *            The last row to shift, 0-based
 * @param n
 *            Number of rows to shift, positive numbers shift down, negative
 *            numbers shift up.
 * @param copyRowHeight
 *            True to copy the row height during the shift
 * @param resetOriginalRowHeight
 *            True to set the original row's height to the default
 */
public void shiftRows(int startRow, int endRow, int n, boolean copyRowHeight, boolean resetOriginalRowHeight) {
    Sheet sheet = getActiveSheet();
    int lastNonBlankRow = getLastNonBlankRow(sheet);
    sheet.shiftRows(startRow, endRow, n, copyRowHeight, resetOriginalRowHeight);
    // need to re-send the cell values to client
    // remove all cached cell data that is now empty
    getFormulaEvaluator().clearAllCachedResultValues();
    int start = n < 0 ? Math.max(lastNonBlankRow, startRow) : startRow;
    int end = n < 0 ? endRow : startRow + n - 1;
    valueManager.updateDeletedRowsInClientCache(start + 1, end + 1);
    int firstAffectedRow = n < 0 ? startRow + n : startRow;
    int lastAffectedRow = n < 0 ? endRow : endRow + n;
    if (copyRowHeight || resetOriginalRowHeight) {
        // might need to increase the size of the row heights array
        int oldLength = getState(false).rowH.length;
        int neededLength = endRow + n + 1;
        if (n > 0 && oldLength < neededLength) {
            getState().rowH = Arrays.copyOf(getState().rowH, neededLength);
        }
        for (int i = firstAffectedRow; i <= lastAffectedRow; i++) {
            Row row = sheet.getRow(i);
            if (row != null) {
                if (row.getZeroHeight()) {
                    getState().rowH[i] = 0f;
                } else {
                    getState().rowH[i] = row.getHeightInPoints();
                }
            } else {
                getState().rowH[i] = sheet.getDefaultRowHeightInPoints();
            }
        }
    }

    if (hasSheetOverlays()) {
        reloadImageSizesFromPOI = true;
    }
    // need to shift the cell styles, clear and update
    // need to go -1 and +1 because of shifted borders..
    final ArrayList<Cell> cellsToUpdate = new ArrayList<Cell>();
    for (int r = (firstAffectedRow - 1); r <= (lastAffectedRow + 1); r++) {
        if (r < 0) {
            r = 0;
        }
        Row row = sheet.getRow(r);
        final Integer rowIndex = new Integer(r + 1);
        if (row == null) {
            valueManager.updateDeletedRowsInClientCache(rowIndex, rowIndex);
            if (getState(false).hiddenRowIndexes.contains(rowIndex)) {
                getState().hiddenRowIndexes.remove(rowIndex);
            }
            for (int c = 0; c < getState().cols; c++) {
                styler.clearCellStyle(r, c);
            }
        } else {
            if (row.getZeroHeight()) {
                getState().hiddenRowIndexes.add(rowIndex);
            } else if (getState(false).hiddenRowIndexes.contains(rowIndex)) {
                getState().hiddenRowIndexes.remove(rowIndex);
            }
            for (int c = 0; c < getState().cols; c++) {
                Cell cell = row.getCell(c);
                if (cell == null) {
                    styler.clearCellStyle(r, c);
                    if (r <= lastNonBlankRow + n) {
                        // There might be a pre-shift value for this cell in
                        // client-side and should be overwritten
                        cell = row.createCell(c);
                        cellsToUpdate.add(cell);
                    }
                } else {
                    cellsToUpdate.add(cell);
                }
            }
        }
    }
    rowsMoved(firstAffectedRow, lastAffectedRow, n);

    for (Cell cell : cellsToUpdate) {
        styler.cellStyleUpdated(cell, false);
        markCellAsUpdated(cell, false);
    }
    styler.loadCustomBorderStylesToState();

    updateMarkedCells(); // deleted and formula cells and style selectors
    updateRowAndColumnRangeCellData(firstRow, firstColumn, lastRow, lastColumn); // shifted area values
    updateMergedRegions();

    CellReference selectedCellReference = selectionManager.getSelectedCellReference();
    if (selectedCellReference != null) {
        if (selectedCellReference.getRow() >= firstAffectedRow
                && selectedCellReference.getRow() <= lastAffectedRow) {
            selectionManager.onSheetAddressChanged(selectedCellReference.formatAsString(), false);
        }
    }
}

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

License:Open Source License

/**
 * Hides or shows the given row, see {@link Row#setZeroHeight(boolean)}.
 * //ww  w  .  j a  v  a 2  s.c o  m
 * @param rowIndex
 *            Index of the target row, 0-based
 * @param hidden
 *            True to hide the target row, false to show it.
 */
public void setRowHidden(int rowIndex, boolean hidden) {
    final Sheet activeSheet = getActiveSheet();
    Row row = activeSheet.getRow(rowIndex);
    if (row == null) {
        row = activeSheet.createRow(rowIndex);
    }
    row.setZeroHeight(hidden);
    if (hidden && !getState().hiddenRowIndexes.contains(rowIndex + 1)) {
        getState().hiddenRowIndexes.add(rowIndex + 1);
        getState().rowH[rowIndex] = 0.0F;
    } else if (!hidden && getState().hiddenRowIndexes.contains(rowIndex + 1)) {
        getState().hiddenRowIndexes.remove(getState().hiddenRowIndexes.indexOf(rowIndex + 1));
        getState().rowH[rowIndex] = row.getHeightInPoints();
    }

    if (hasSheetOverlays()) {
        reloadImageSizesFromPOI = true;
        loadOrUpdateOverlays();
    }
}

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

License:Open Source License

private void handleRowSizes(Set<Integer> rowsWithComponents) {
    // Set larger height for new rows with components
    for (Integer row : rowsWithComponents) {
        if (isRowHidden(row)) {
            continue;
        }/*from  w  w  w .j a  v  a 2s.  c  om*/
        float currentHeight = getState(false).rowH[row];
        if (currentHeight < getMinimumRowHeightForComponents()) {
            getState().rowH[row] = getMinimumRowHeightForComponents();
        }
    }
    // Reset row height for rows which no longer have components
    if (this.rowsWithComponents != null) {
        Sheet activeSheet = getActiveSheet();
        for (Integer row : this.rowsWithComponents) {
            if (!rowsWithComponents.contains(row)) {
                if (isRowHidden(row)) {
                    getState().rowH[row] = 0;
                } else {
                    Row r = activeSheet.getRow(row);
                    if (r == null) {
                        getState().rowH[row] = activeSheet.getDefaultRowHeightInPoints();
                    } else {
                        getState().rowH[row] = r.getHeightInPoints();
                    }
                }
            }
        }
    }

    this.rowsWithComponents = rowsWithComponents;
}

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

License:Open Source License

/**
 * Calculate size-related values for the sheet. Includes row and column
 * counts, actual row heights and column widths, and hidden row and column
 * indexes.//from   w w  w .  ja va  2 s. c  om
 * 
 * @param spreadsheet
 * @param sheet
 */
static void calculateSheetSizes(final Spreadsheet spreadsheet, final Sheet sheet) {
    // Always have at least the default amount of rows
    int rows = sheet.getLastRowNum() + 1;
    if (rows < spreadsheet.getDefaultRowCount()) {
        rows = spreadsheet.getDefaultRowCount();
    }
    spreadsheet.getState().rows = rows;

    final float[] rowHeights = new float[rows];
    int cols = 0;
    int tempRowIndex = -1;
    final ArrayList<Integer> hiddenRowIndexes = new ArrayList<Integer>();
    for (Row row : sheet) {
        int rIndex = row.getRowNum();
        // set the empty rows to have the default row width
        while (++tempRowIndex != rIndex) {
            rowHeights[tempRowIndex] = spreadsheet.getState().defRowH;
        }
        if (row.getZeroHeight()) {
            rowHeights[rIndex] = 0.0F;
            hiddenRowIndexes.add(rIndex + 1);
        } else {
            rowHeights[rIndex] = row.getHeightInPoints();
        }
        int c = row.getLastCellNum();
        if (c > cols) {
            cols = c;
        }
    }
    if (rows > sheet.getLastRowNum() + 1) {
        float defaultRowHeightInPoints = sheet.getDefaultRowHeightInPoints();

        int lastRowNum = sheet.getLastRowNum();
        // if sheet is empty, also set height for 'last row' (index
        // zero)
        if (lastRowNum == 0) {
            rowHeights[0] = defaultRowHeightInPoints;
        }

        // set default height for the rest
        for (int i = lastRowNum + 1; i < rows; i++) {
            rowHeights[i] = defaultRowHeightInPoints;
        }
    }
    spreadsheet.getState().hiddenRowIndexes = hiddenRowIndexes;
    spreadsheet.getState().rowH = rowHeights;

    // Always have at least the default amount of columns
    if (cols < spreadsheet.getDefaultColumnCount()) {
        cols = spreadsheet.getDefaultColumnCount();
    }
    spreadsheet.getState().cols = cols;

    final int[] colWidths = new int[cols];
    final ArrayList<Integer> hiddenColumnIndexes = new ArrayList<Integer>();
    for (int i = 0; i < cols; i++) {
        if (sheet.isColumnHidden(i)) {
            colWidths[i] = 0;
            hiddenColumnIndexes.add(i + 1);
        } else {
            colWidths[i] = ExcelToHtmlUtils.getColumnWidthInPx(sheet.getColumnWidth(i));
        }
    }
    spreadsheet.getState().hiddenColumnIndexes = hiddenColumnIndexes;
    spreadsheet.getState().colW = colWidths;
}