Example usage for org.apache.poi.ss.usermodel Sheet getDefaultRowHeightInPoints

List of usage examples for org.apache.poi.ss.usermodel Sheet getDefaultRowHeightInPoints

Introduction

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

Prototype

float getDefaultRowHeightInPoints();

Source Link

Document

Get the default row height for the sheet (if the rows do not define their own height) in points.

Usage

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

License:Open Source License

@SuppressWarnings("rawtypes")
public static void exportToExcel(String[][] table, ExportMode exportMode) throws IOException {
    Class[] types = getTypes(table);
    Workbook wb = new XSSFWorkbook();
    Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
    CellStyle style;/*  ww  w . j a v a2s . c  o  m*/
    DataFormat df = wb.createDataFormat();

    Font font = wb.createFont();
    font.setFontName("Serif");
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    font.setFontHeightInPoints((short) 15);
    style = wb.createCellStyle();
    style.setFont(font);
    styles.put("title", style);

    font = wb.createFont();
    font.setFontName("Serif");
    font.setFontHeightInPoints((short) 10);
    style = wb.createCellStyle();
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderBottom(CellStyle.BORDER_THIN);
    style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderTop(CellStyle.BORDER_THIN);
    style.setTopBorderColor(IndexedColors.BLACK.getIndex());
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setFont(font);
    style.setWrapText(true);
    style.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    styles.put("th", style);

    font = wb.createFont();
    font.setFontName("Serif");
    font.setFontHeightInPoints((short) 9);
    style = wb.createCellStyle();
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    style.setAlignment(CellStyle.ALIGN_LEFT);
    style.setFont(font);
    style.setWrapText(true);
    style.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    styles.put("td", style);

    font = wb.createFont();
    font.setFontName("Serif");
    font.setFontHeightInPoints((short) 9);
    style = wb.createCellStyle();
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderTop(CellStyle.BORDER_THIN);
    style.setTopBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderBottom(CellStyle.BORDER_THIN);
    style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
    style.setAlignment(CellStyle.ALIGN_LEFT);
    style.setFont(font);
    style.setWrapText(true);
    style.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    styles.put("td-border", style);

    font = wb.createFont();
    font.setFontName("Serif");
    font.setFontHeightInPoints((short) 9);
    style = wb.createCellStyle();
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setFont(font);
    style.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    styles.put("td-double", style);

    font = wb.createFont();
    font.setFontName("Serif");
    font.setFontHeightInPoints((short) 9);
    style = wb.createCellStyle();
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setFont(font);
    style.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    styles.put("td-right", style);

    font = wb.createFont();
    font.setFontName("Serif");
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    font.setFontHeightInPoints((short) 9);
    style = wb.createCellStyle();
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setFont(font);
    style.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    styles.put("td-bold", style);

    font = wb.createFont();
    font.setFontName("Serif");
    font.setFontHeightInPoints((short) 9);
    style = wb.createCellStyle();
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setFont(font);
    style.setDataFormat(df.getFormat("d.mm.yyyy h:MM"));
    style.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    styles.put("td-date", style);

    Sheet sheet = wb.createSheet();
    sheet.setFitToPage(true);

    Cell cell;

    int maxRows = 0;
    for (int r = 0; r < table.length; r++) {
        Row row = sheet.createRow(r);
        if (r == 0) {
            row.setRowStyle(styles.get("th"));
        }

        int rows = 1;
        for (int c = 0; c < table[r].length; c++) {
            cell = row.createCell(c);
            String s = table[r][c];
            if (s == null)
                continue;
            rows = Math.max(rows, s.split("\n").length);
            try {
                if (exportMode == ExportMode.HEADERS_TOP && r == 0) {
                    cell.setCellStyle(styles.get("th"));
                    cell.setCellValue(s);

                } else if (exportMode == ExportMode.HEADERS_TOPLEFT && (r == 0 || c == 0)) {
                    if (r == 0 && c == 0) {
                        cell.setCellStyle(styles.get("td"));
                    } else {
                        cell.setCellStyle(styles.get("th"));
                    }
                    cell.setCellValue(s);
                } else if (types[c] == Double.class) {
                    cell.setCellStyle(styles.get("td-double"));
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(Double.parseDouble(s));
                } else if (types[c] == String.class) {
                    cell.setCellStyle(
                            styles.get(exportMode == ExportMode.HEADERS_TOPLEFT ? "td-border" : "td"));
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(s);
                } else {
                    cell.setCellStyle(styles.get("td-right"));
                    cell.setCellValue(s);
                }
            } catch (Exception e) {
                cell.setCellStyle(styles.get("td"));
                cell.setCellValue(s);
            }
        }
        maxRows = Math.max(maxRows, rows);
        row.setHeightInPoints(rows * 16f);

    }

    // Add footer notes
    if (footerData.size() > 0) {
        Row row = sheet.createRow(table.length);
        row.setHeightInPoints((footerData.size() * sheet.getDefaultRowHeightInPoints()));
        cell = row.createCell(0);
        sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), //first row (0-based)
                row.getRowNum(), //last row  (0-based)
                0, //first column (0-based)
                table[0].length - 1 //last column  (0-based)
        ));
        //for ( String data : footerData ) {
        style = wb.createCellStyle();
        style.setWrapText(true);
        cell.setCellStyle(style);
        cell.setCellValue(MiscUtils.flatten(footerData, "\n"));
        //}
    }
    footerData.clear();

    autoSizeColumns(sheet);
    if (table.length > 0) {
        for (int c = 0; c < table[0].length; c++) {
            if (sheet.getColumnWidth(c) > 10000)
                sheet.setColumnWidth(c, 3000);
        }
    }

    if (exportMode == ExportMode.HEADERS_TOPLEFT) {
        for (int r = 1; r < table.length; r++) {
            sheet.getRow(r).setHeightInPoints(maxRows * 16f);
        }
    }

    File reportFile = IOUtils.createTempFile("export_", ".xlsx");
    FileOutputStream out = new FileOutputStream(reportFile);
    wb.write(out);
    wb.close();
    out.close();
    Desktop.getDesktop().open(reportFile);
}

From source file:com.miraisolutions.xlconnect.Workbook.java

License:Open Source License

public void setRowHeight(int sheetIndex, int rowIndex, float height) {
    Sheet sheet = getSheet(sheetIndex);
    Row r = sheet.getRow(rowIndex);/* ww w .j  a v a 2  s .  c om*/
    if (r == null)
        r = getSheet(sheetIndex).createRow(rowIndex);

    if (height >= 0)
        r.setHeightInPoints(height);
    else
        r.setHeightInPoints(sheet.getDefaultRowHeightInPoints());
}

From source file:com.quanticate.opensource.datalistdownload.DataListDownloadWebScript.java

License:Open Source License

@Override
protected void populateBody(Object resource, Workbook workbook, Sheet sheet, List<QName> properties)
        throws IOException {
    NodeRef list = (NodeRef) resource;//from w ww.  java 2  s . co  m
    List<NodeRef> items = getItems(list);

    // Our various formats
    DataFormat formatter = workbook.createDataFormat();

    CellStyle styleInt = workbook.createCellStyle();
    styleInt.setDataFormat(formatter.getFormat("0"));
    CellStyle styleDate = workbook.createCellStyle();
    styleDate.setDataFormat(formatter.getFormat("yyyy-mm-dd"));
    CellStyle styleDouble = workbook.createCellStyle();
    styleDouble.setDataFormat(formatter.getFormat("General"));
    CellStyle styleNewLines = workbook.createCellStyle();
    styleNewLines.setWrapText(true);

    // Export the items
    int rowNum = 1, colNum = 0;
    for (NodeRef item : items) {
        Row r = sheet.createRow(rowNum);

        colNum = 0;
        for (QName prop : properties) {
            Cell c = r.createCell(colNum);

            Pair<Object, String> valAndLink = identifyValueAndLink(item, prop);

            if (valAndLink == null) {
                // This property isn't set
                c.setCellType(Cell.CELL_TYPE_BLANK);
            } else {
                Object val = valAndLink.getFirst();

                // Multi-line property?
                if (val instanceof String[]) {
                    String[] lines = (String[]) val;
                    StringBuffer text = new StringBuffer();

                    for (String line : lines) {
                        if (text.length() > 0) {
                            text.append('\n');
                        }
                        text.append(line);
                    }

                    String v = text.toString();
                    c.setCellValue(v);
                    if (lines.length > 1) {
                        c.setCellStyle(styleNewLines);
                        r.setHeightInPoints(lines.length * sheet.getDefaultRowHeightInPoints());
                    }
                }

                // Regular properties
                else if (val instanceof String) {
                    c.setCellValue((String) val);
                } else if (val instanceof Date) {
                    c.setCellValue((Date) val);
                    c.setCellStyle(styleDate);
                } else if (val instanceof Integer || val instanceof Long) {
                    double v = 0.0;
                    if (val instanceof Long)
                        v = (double) (Long) val;
                    if (val instanceof Integer)
                        v = (double) (Integer) val;
                    c.setCellValue(v);
                    c.setCellStyle(styleInt);
                } else if (val instanceof Float || val instanceof Double) {
                    double v = 0.0;
                    if (val instanceof Float)
                        v = (double) (Float) val;
                    if (val instanceof Double)
                        v = (double) (Double) val;
                    c.setCellValue(v);
                    c.setCellStyle(styleDouble);
                } else {
                    // TODO
                    System.err
                            .println("TODO: Handle Excel output of " + val.getClass().getName() + " - " + val);
                }
            }

            colNum++;
        }

        rowNum++;
    }

    // Sensible column widths please!
    colNum = 0;
    for (QName prop : properties) {
        sheet.autoSizeColumn(colNum);
        colNum++;
    }
}

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 .j a  va2 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

/**
 * Deletes rows. See {@link Sheet#removeRow(Row)}. Removes all row content,
 * deletes cells and resets the sheet size.
 * /*from   w  ww  .  j  a v a  2s. c om*/
 * Does not shift rows up (!) - use
 * {@link #shiftRows(int, int, int, boolean, boolean)} for that.
 * 
 * @param startRow
 *            Index of the starting row, 0-based
 * @param endRow
 *            Index of the ending row, 0-based
 */
public void deleteRows(int startRow, int endRow) {
    Sheet sheet = getActiveSheet();
    for (int i = startRow; i <= endRow; i++) {
        Row row = sheet.getRow(i);
        if (row != null) {
            getActiveSheet().removeRow(row);
        }
    }
    for (int i = startRow; i <= endRow; i++) {
        getState(false).rowH[i] = sheet.getDefaultRowHeightInPoints();
    }
    updateMergedRegions();
    valueManager.updateDeletedRowsInClientCache(startRow + 1, endRow + 1);

    if (hasSheetOverlays()) {
        reloadImageSizesFromPOI = true;
    }
    updateMarkedCells();
    CellReference selectedCellReference = getSelectedCellReference();
    if (selectedCellReference.getRow() >= startRow && selectedCellReference.getRow() <= endRow) {
        selectionManager.reSelectSelectedCell();
    }

}

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  ww w.  ja v a 2s  .  c o  m
        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 . j  a  v  a  2  s . co m
 * 
 * @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;
}

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

License:Open Source License

private static void setDefaultRowHeight(Spreadsheet spreadsheet, final Sheet sheet) {
    float defaultRowHeightInPoints = sheet.getDefaultRowHeightInPoints();
    if (defaultRowHeightInPoints <= 0) {
        sheet.setDefaultRowHeightInPoints(DEFAULT_ROW_HEIGHT_POINTS);
        spreadsheet.getState().defRowH = DEFAULT_ROW_HEIGHT_POINTS;
    } else {//from w ww .j  av  a  2  s .  c  o  m
        spreadsheet.getState().defRowH = defaultRowHeightInPoints;
    }
}

From source file:de.fme.alfresco.repo.web.scripts.datalist.DataListDownloadWebScript.java

License:Open Source License

@SuppressWarnings("deprecation")
@Override//  w w w  . j a v  a 2s .com
protected void populateBody(Object resource, Workbook workbook, Sheet sheet, List<QName> properties)
        throws IOException {
    NodeRef list = (NodeRef) resource;
    List<NodeRef> items = getItems(list);

    // Our various formats
    DataFormat formatter = workbook.createDataFormat();
    CreationHelper createHelper = workbook.getCreationHelper();

    CellStyle styleInt = workbook.createCellStyle();
    styleInt.setDataFormat(formatter.getFormat("0"));
    CellStyle styleDate = workbook.createCellStyle();
    styleDate.setDataFormat(formatter.getFormat("yyyy-mm-dd"));
    CellStyle styleDouble = workbook.createCellStyle();
    styleDouble.setDataFormat(formatter.getFormat("General"));
    CellStyle styleNewLines = workbook.createCellStyle();
    styleNewLines.setWrapText(true);

    CellStyle hlink_style = workbook.createCellStyle();
    Font hlink_font = workbook.createFont();
    hlink_font.setUnderline(Font.U_SINGLE);
    hlink_font.setColor(IndexedColors.BLUE.getIndex());
    hlink_style.setFont(hlink_font);

    // Export the items
    int rowNum = 1, colNum = 0;
    for (NodeRef item : items) {
        Row r = sheet.createRow(rowNum);

        colNum = 0;
        for (QName prop : properties) {
            Cell c = r.createCell(colNum);

            Serializable val = nodeService.getProperty(item, prop);
            if (val == null) {
                // Is it an association, or just missing?
                List<AssociationRef> assocs = nodeService.getTargetAssocs(item, prop);
                Set<QName> qnames = new HashSet<QName>(1, 1.0f);
                qnames.add(prop);
                List<ChildAssociationRef> childAssocs = nodeService.getChildAssocs(item, qnames);
                if (assocs.size() > 0) {
                    StringBuffer text = new StringBuffer();
                    int lines = 1;

                    for (AssociationRef ref : assocs) {
                        NodeRef child = ref.getTargetRef();
                        QName type = nodeService.getType(child);
                        if (ContentModel.TYPE_PERSON.equals(type)) {
                            if (text.length() > 0) {
                                text.append('\n');
                                lines++;
                            }
                            text.append(nodeService.getProperty(child, ContentModel.PROP_FIRSTNAME));
                            text.append(" ");
                            text.append(nodeService.getProperty(child, ContentModel.PROP_LASTNAME));
                        } else if (ContentModel.TYPE_CONTENT.equals(type)) {
                            // TODO Link to the content
                            if (text.length() > 0) {
                                text.append('\n');
                                lines++;
                            }
                            text.append(nodeService.getProperty(child, ContentModel.PROP_NAME));
                            text.append(" (");
                            text.append(nodeService.getProperty(child, ContentModel.PROP_TITLE));
                            text.append(") ");
                            /*MessageFormat.format(CONTENT_DOWNLOAD_PROP_URL, new Object[] {
                                    child.getStoreRef().getProtocol(),
                                    child.getStoreRef().getIdentifier(),
                                    child.getId(),
                                    URLEncoder.encode((String)nodeService.getProperty(child, ContentModel.PROP_TITLE)),
                                    URLEncoder.encode(ContentModel.PROP_CONTENT.toString()) });
                            */
                            /*currently only one link per cell possible
                             * Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_URL);
                             *link.setAddress("http://poi.apache.org/");
                             *c.setHyperlink(link);
                             *c.setCellStyle(hlink_style);*/
                        } else if (ApplicationModel.TYPE_FILELINK.equals(type)) {
                            NodeRef linkRef = (NodeRef) nodeService.getProperty(child,
                                    ContentModel.PROP_LINK_DESTINATION);
                            if (linkRef != null) {
                                if (text.length() > 0) {
                                    text.append('\n');
                                    lines++;
                                }
                                text.append("link to: ");
                                try {
                                    text.append(nodeService.getProperty(linkRef, ContentModel.PROP_NAME));
                                    text.append(" (");
                                    text.append(nodeService.getProperty(linkRef, ContentModel.PROP_TITLE));
                                    text.append(") ");
                                } catch (Exception e) {
                                    text.append(nodeService.getProperty(child, ContentModel.PROP_NAME));
                                    text.append(" (");
                                    text.append(nodeService.getProperty(child, ContentModel.PROP_TITLE));
                                    text.append(") ");

                                }
                            }
                        } else {
                            System.err.println("TODO: handle " + type + " for " + child);
                        }
                    }

                    String v = text.toString();
                    c.setCellValue(v);
                    if (lines > 1) {
                        c.setCellStyle(styleNewLines);
                        r.setHeightInPoints(lines * sheet.getDefaultRowHeightInPoints());
                    }
                } else if (childAssocs.size() > 0) {
                    StringBuffer text = new StringBuffer();
                    for (ChildAssociationRef childAssociationRef : childAssocs) {
                        NodeRef child = childAssociationRef.getChildRef();
                        QName type = nodeService.getType(child);
                        if (type.equals(ForumModel.TYPE_FORUM)) {
                            List<ChildAssociationRef> topics = nodeService.getChildAssocs(child);
                            if (topics.size() > 0) {
                                ChildAssociationRef topicRef = topics.get(0);
                                List<ChildAssociationRef> comments = nodeService
                                        .getChildAssocs(topicRef.getChildRef());
                                for (ChildAssociationRef commentChildRef : comments) {
                                    NodeRef commentRef = commentChildRef.getChildRef();

                                    ContentData data = (ContentData) nodeService.getProperty(commentRef,
                                            ContentModel.PROP_CONTENT);
                                    TemplateContentData contentData = new TemplateContentData(data,
                                            ContentModel.PROP_CONTENT);

                                    String commentString = "";
                                    try {
                                        commentString = contentData.getContentAsText(commentRef, -1);
                                    } catch (Exception e) {
                                        logger.warn("failed to extract content for nodeRef " + commentRef, e);
                                    }

                                    String creator = (String) nodeService.getProperty(commentRef,
                                            ContentModel.PROP_CREATOR);
                                    NodeRef person = personService.getPerson(creator, false);
                                    if (person != null) {
                                        creator = nodeService.getProperty(person, ContentModel.PROP_FIRSTNAME)
                                                + " "
                                                + nodeService.getProperty(person, ContentModel.PROP_LASTNAME);
                                    }
                                    Date created = (Date) nodeService.getProperty(commentRef,
                                            ContentModel.PROP_CREATED);

                                    text.append(creator).append(" (")
                                            .append(DateFormatUtils.format(created, "yyyy-MM-dd"))
                                            .append("):\n ");
                                    text.append(commentString).append("\n");
                                }
                            }
                        }
                    }
                    String v = text.toString();
                    c.setCellValue(v);
                    c.setCellStyle(styleNewLines);

                } else {
                    // This property isn't set
                    c.setCellType(Cell.CELL_TYPE_BLANK);
                }
            } else {
                // Regular property, set
                if (val instanceof String) {
                    c.setCellValue((String) val);
                    c.setCellStyle(styleNewLines);
                } else if (val instanceof Date) {
                    c.setCellValue((Date) val);
                    c.setCellStyle(styleDate);
                } else if (val instanceof Integer || val instanceof Long) {
                    double v = 0.0;
                    if (val instanceof Long)
                        v = (double) (Long) val;
                    if (val instanceof Integer)
                        v = (double) (Integer) val;
                    c.setCellValue(v);
                    c.setCellStyle(styleInt);
                } else if (val instanceof Float || val instanceof Double) {
                    double v = 0.0;
                    if (val instanceof Float)
                        v = (double) (Float) val;
                    if (val instanceof Double)
                        v = (double) (Double) val;
                    c.setCellValue(v);
                    c.setCellStyle(styleDouble);
                } else {
                    // TODO
                    System.err.println("TODO: handle " + val.getClass().getName() + " - " + val);
                }
            }

            colNum++;
        }

        rowNum++;
    }

    // Sensible column widths please!
    colNum = 0;
    for (QName prop : properties) {
        try {
            sheet.autoSizeColumn(colNum);
        } catch (IllegalArgumentException e) {
            sheet.setColumnWidth(colNum, 40 * 256);
        }

        colNum++;
    }
}

From source file:org.alfresco.repo.web.scripts.datalist.DataListDownloadWebScript.java

License:Open Source License

@Override
protected void populateBody(Object resource, Workbook workbook, Sheet sheet, List<QName> properties)
        throws IOException {
    NodeRef list = (NodeRef) resource;//from   w w w  .j  a  v  a  2s  .c o  m
    List<NodeRef> items = getItems(list);

    // Our various formats
    DataFormat formatter = workbook.createDataFormat();

    CellStyle styleInt = workbook.createCellStyle();
    styleInt.setDataFormat(formatter.getFormat("0"));
    CellStyle styleDate = workbook.createCellStyle();
    styleDate.setDataFormat(formatter.getFormat("yyyy-mm-dd"));
    CellStyle styleDouble = workbook.createCellStyle();
    styleDouble.setDataFormat(formatter.getFormat("General"));
    CellStyle styleNewLines = workbook.createCellStyle();
    styleNewLines.setWrapText(true);

    // Export the items
    int rowNum = 1, colNum = 0;
    for (NodeRef item : items) {
        Row r = sheet.createRow(rowNum);

        colNum = 0;
        for (QName prop : properties) {
            Cell c = r.createCell(colNum);

            Serializable val = nodeService.getProperty(item, prop);
            if (val == null) {
                // Is it an association, or just missing?
                List<AssociationRef> assocs = nodeService.getTargetAssocs(item, prop);
                if (assocs.size() > 0) {
                    StringBuffer text = new StringBuffer();
                    int lines = 1;

                    for (AssociationRef ref : assocs) {
                        NodeRef child = ref.getTargetRef();
                        QName type = nodeService.getType(child);
                        if (ContentModel.TYPE_PERSON.equals(type)) {
                            if (text.length() > 0) {
                                text.append('\n');
                                lines++;
                            }
                            text.append(nodeService.getProperty(child, ContentModel.PROP_USERNAME));
                        } else if (ContentModel.TYPE_CONTENT.equals(type)) {
                            // TODO Link to the content
                            if (text.length() > 0) {
                                text.append('\n');
                                lines++;
                            }
                            text.append(nodeService.getProperty(child, ContentModel.PROP_TITLE));
                        } else {
                            System.err.println("TODO: handle " + type + " for " + child);
                        }
                    }

                    String v = text.toString();
                    c.setCellValue(v);
                    if (lines > 1) {
                        c.setCellStyle(styleNewLines);
                        r.setHeightInPoints(lines * sheet.getDefaultRowHeightInPoints());
                    }
                } else {
                    // This property isn't set
                    c.setCellType(Cell.CELL_TYPE_BLANK);
                }
            } else {
                // Regular property, set
                if (val instanceof String) {
                    c.setCellValue((String) val);
                } else if (val instanceof Date) {
                    c.setCellValue((Date) val);
                    c.setCellStyle(styleDate);
                } else if (val instanceof Integer || val instanceof Long) {
                    double v = 0.0;
                    if (val instanceof Long)
                        v = (double) (Long) val;
                    if (val instanceof Integer)
                        v = (double) (Integer) val;
                    c.setCellValue(v);
                    c.setCellStyle(styleInt);
                } else if (val instanceof Float || val instanceof Double) {
                    double v = 0.0;
                    if (val instanceof Float)
                        v = (double) (Float) val;
                    if (val instanceof Double)
                        v = (double) (Double) val;
                    c.setCellValue(v);
                    c.setCellStyle(styleDouble);
                } else {
                    // TODO
                    System.err.println("TODO: handle " + val.getClass().getName() + " - " + val);
                }
            }

            colNum++;
        }

        rowNum++;
    }

    // Sensible column widths please!
    colNum = 0;
    for (QName prop : properties) {
        sheet.autoSizeColumn(colNum);
        colNum++;
    }
}