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

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

Introduction

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

Prototype

void setHeightInPoints(float height);

Source Link

Document

Set the row's height in points.

Usage

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./*w w  w .  j  a  va2 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.vaadin.addon.spreadsheet.Spreadsheet.java

License:Open Source License

/**
 * Sets the row height for currently active sheet. Updates both POI model
 * and the visible sheet./*from www .  j  a  v a 2 s .  c o m*/
 * 
 * @param index
 *            Index of target row, 0-based
 * @param height
 *            New row height in points
 */
public void setRowHeight(int index, float height) {
    if (height == 0.0F) {
        setRowHidden(index, true);
    } else {
        Row row = getActiveSheet().getRow(index);
        if (getState().hiddenRowIndexes.contains(Integer.valueOf(index + 1))) {
            getState().hiddenRowIndexes.remove(Integer.valueOf(index + 1));
            if (row != null && row.getZeroHeight()) {
                row.setZeroHeight(false);
            }
        }
        getState().rowH[index] = height;
        if (row == null) {
            row = getActiveSheet().createRow(index);
        }
        row.setHeightInPoints(height);
    }
}

From source file:com.vincestyling.apkinfoextractor.core.export.ExportToExcel.java

License:Apache License

@Override
public void export() throws Exception {
    Workbook wb = new HSSFWorkbook();

    Map<String, CellStyle> styles = createStyles(wb);

    Sheet sheet = wb.createSheet(Constancts.APP_NAME);
    sheet.setHorizontallyCenter(true);//from   w  w  w .j av  a 2s. c om
    sheet.setFitToPage(true);

    Row titleRow = sheet.createRow(0);
    titleRow.setHeightInPoints(45);
    Cell titleCell = titleRow.createCell(0);
    titleCell.setCellValue(
            "  File generated by ApkInfoExtractor (https://github.com/vince-styling/ApkInfoExtractor), Copyright (C) 2014 Vince Styling");
    titleCell.setCellStyle(styles.get("title"));

    Row headerRow = sheet.createRow(1);
    headerRow.setHeightInPoints(40);

    int cellNum = 0;
    String[] fields = solution.getExtractFields().split(",");
    for (String field : fields) {
        if (field.equals(Constancts.ICON))
            continue;
        Cell headerCell = headerRow.createCell(cellNum);
        headerCell.setCellValue(field);
        headerCell.setCellStyle(styles.get("header"));
        sheet.setColumnWidth(cellNum, ApkInfo.getFieldCharacterCount(field) * 256);
        cellNum++;
    }

    int rowNum = 2;
    for (int i = 0; i < solution.getResultCount(); i++) {
        ResultDataProvider provider = solution.getResultList().get(i);
        postProgress(i + 1);

        cellNum = 0;
        Row row = sheet.createRow(rowNum++);
        for (String field : fields) {
            if (field.equals(Constancts.ICON))
                continue;
            Cell cell = row.createCell(cellNum);
            cell.setCellStyle(styles.get("cell"));
            String value = getFieldValue(provider.getApkInfo(), field);
            cell.setCellValue(value);
            cellNum++;
        }
        row.setHeight((short) (5 * 256));
    }

    File outputFile = new File(solution.getWorkingFolder(), solution.generateOutputFileName() + ".xls");
    FileOutputStream out = new FileOutputStream(outputFile);
    wb.write(out);
    out.close();

    callback.onProcessSuccess(outputFile);
}

From source file:com.wantdo.stat.excel.poi_src.AligningCells.java

License:Apache License

public static void main(String[] args) throws IOException {
    Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();

    Sheet sheet = wb.createSheet();//from ww  w  .j a v  a2s  .c o  m
    Row row = sheet.createRow((short) 2);
    row.setHeightInPoints(30);
    for (int i = 0; i < 8; i++) {
        //column width is set in units of 1/256th of a character width
        sheet.setColumnWidth(i, 256 * 15);
    }

    createCell(wb, row, (short) 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_BOTTOM);
    createCell(wb, row, (short) 1, CellStyle.ALIGN_CENTER_SELECTION, CellStyle.VERTICAL_BOTTOM);
    createCell(wb, row, (short) 2, CellStyle.ALIGN_FILL, CellStyle.VERTICAL_CENTER);
    createCell(wb, row, (short) 3, CellStyle.ALIGN_GENERAL, CellStyle.VERTICAL_CENTER);
    createCell(wb, row, (short) 4, CellStyle.ALIGN_JUSTIFY, CellStyle.VERTICAL_JUSTIFY);
    createCell(wb, row, (short) 5, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_TOP);
    createCell(wb, row, (short) 6, CellStyle.ALIGN_RIGHT, CellStyle.VERTICAL_TOP);

    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream("ss-example-align.xlsx");
    wb.write(fileOut);
    fileOut.close();
}

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

License:Open Source License

@SuppressWarnings("deprecation")
@Override/*from  w  ww. ja v a2s  .  c  o m*/
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:de.fraunhofer.sciencedataamanager.datamanager.SearchDefinitonExecutionDataManager.java

/**
 *
 * @param searchDefinitonExecutionList//from w w w . ja  v a  2s .c  o m
 * @param outputStream
 * @throws Exception
 */
public void exportToExcel(LinkedList<SearchDefinitonExecution> searchDefinitonExecutionList,
        OutputStream outputStream) throws Exception {

    Workbook currentWorkBook = new HSSFWorkbook();
    int currenSheetCount = 0;
    for (SearchDefinitonExecution searchDefinitonExecution : searchDefinitonExecutionList) {

        Sheet currentSheet = currentWorkBook.createSheet();
        currentSheet.setFitToPage(true);
        currentSheet.setHorizontallyCenter(true);
        currentSheet.createFreezePane(0, 1);
        currentWorkBook.setSheetName(currenSheetCount, searchDefinitonExecution.getSystemInstance().getName());

        Row headerRow = currentSheet.createRow(0);
        headerRow.setHeightInPoints(12.75f);

        headerRow.createCell(0).setCellValue("ID");
        headerRow.createCell(1).setCellValue("Title");

        headerRow.createCell(2).setCellValue("Identifier 1");
        headerRow.createCell(3).setCellValue("Identifier 2");
        headerRow.createCell(4).setCellValue("Identifier 3");
        headerRow.createCell(5).setCellValue("Identifier 4");
        headerRow.createCell(6).setCellValue("Url 1");
        headerRow.createCell(7).setCellValue("Url 2");
        headerRow.createCell(8).setCellValue("Text 1");
        headerRow.createCell(9).setCellValue("Publication Name");
        headerRow.createCell(10).setCellValue("Issue Name");
        headerRow.createCell(11).setCellValue("Publish Date");
        headerRow.createCell(12).setCellValue("Volume");
        headerRow.createCell(13).setCellValue("Start Page");
        headerRow.createCell(14).setCellValue("Issue Identifier");

        CellStyle style = currentWorkBook.createCellStyle();
        Font headerFont = currentWorkBook.createFont();
        headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);

        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.LIGHT_CORNFLOWER_BLUE.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setFont(headerFont);

        headerRow.setRowStyle(style);

        Row currentRow = null;
        int rowNum = 1;
        for (ScientificPaperMetaInformation scientificPaperMetaInformation : searchDefinitonExecution
                .getScientificPaperMetaInformation()) {
            currentRow = currentSheet.createRow(rowNum);
            currentRow.createCell(0).setCellValue(scientificPaperMetaInformation.getID());
            currentRow.createCell(1).setCellValue(scientificPaperMetaInformation.getTitle());
            currentRow.createCell(2).setCellValue(scientificPaperMetaInformation.getIdentifier_1());
            currentRow.createCell(3).setCellValue(scientificPaperMetaInformation.getIdentifier_2());
            currentRow.createCell(4).setCellValue(scientificPaperMetaInformation.getIdentifier_3());
            currentRow.createCell(5).setCellValue(scientificPaperMetaInformation.getIdentifier_4());
            currentRow.createCell(6).setCellValue(scientificPaperMetaInformation.getUrl_1());
            currentRow.createCell(7).setCellValue(scientificPaperMetaInformation.getUrl_2());
            currentRow.createCell(8).setCellValue(scientificPaperMetaInformation.getText_1());

            currentRow.createCell(9).setCellValue(scientificPaperMetaInformation.getSrcTitle());
            currentRow.createCell(10).setCellValue(scientificPaperMetaInformation.getScrPublisherName());
            currentRow.createCell(11).setCellValue(scientificPaperMetaInformation.getSrcPublicationDate());
            currentRow.createCell(12).setCellValue(scientificPaperMetaInformation.getSrcVolume());
            currentRow.createCell(13).setCellValue(scientificPaperMetaInformation.getSrcStartPage());
            currentRow.createCell(14).setCellValue(scientificPaperMetaInformation.getScrIdentifier_1());

            rowNum++;

        }
        currenSheetCount++;
    }
    currentWorkBook.write(outputStream);

    outputStream.close();

}

From source file:de.fraunhofer.sciencedataamanager.exampes.export.ExcelDataExport.java

/**
 *
 * @param dataToExport The objects gets all the values, which should
 * exported.//www. j av a2  s .co  m
 * @param outputStream
 * @throws Exception
 */
@Override
public void export(Map<String, Map<String, List<Object>>> allConnectorsToExport, OutputStream outputStream)
        throws Exception {
    Workbook currentWorkBook = new HSSFWorkbook();
    int currenSheetCount = 0;

    for (String currentKey : allConnectorsToExport.keySet()) {
        Map<String, List<Object>> dataToExport = allConnectorsToExport.get(currentKey);
        List<String> columns = new ArrayList<String>(dataToExport.keySet());
        List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
        int size = dataToExport.values().iterator().next().size();

        for (int i = 0; i < size; i++) {
            Map<String, Object> row = new HashMap<String, Object>();

            for (String column : columns) {
                row.put(column, dataToExport.get(column).get(i));
            }

            rows.add(row);
        }

        //for (SearchDefinitonExecution searchDefinitonExecution : searchDefinitonExecutionList) {
        Sheet currentSheet = currentWorkBook.createSheet();
        currentSheet.setFitToPage(true);
        currentSheet.setHorizontallyCenter(true);
        currentSheet.createFreezePane(0, 1);
        currentWorkBook.setSheetName(currenSheetCount, currentKey);

        Row headerRow = currentSheet.createRow(0);
        headerRow.setHeightInPoints(12.75f);
        int headerColumnIndex = 0;
        for (String currentColumn : columns) {
            headerRow.createCell(headerColumnIndex).setCellValue(currentColumn);
            headerColumnIndex++;
        }
        CellStyle style = currentWorkBook.createCellStyle();
        Font headerFont = currentWorkBook.createFont();
        headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);

        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.LIGHT_CORNFLOWER_BLUE.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setFont(headerFont);

        headerRow.setRowStyle(style);

        Row currentRow = null;
        int rowNum = 1;
        int currentColum = 0;

        for (Map<String, Object> currentRow2 : rows) {
            currentRow = currentSheet.createRow(rowNum);
            for (String column : columns) {
                if (currentRow2.get(column) != null) {
                    currentRow.createCell(currentColum).setCellValue(currentRow2.get(column).toString());
                }
                currentColum++;

            }
            currentColum = 0;
            rowNum++;
        }
        currenSheetCount++;
    }
    currentWorkBook.write(outputStream);

    outputStream.close();

}

From source file:de.maklerpoint.office.Schnittstellen.Excel.ExportExcelXLSX.java

License:Open Source License

public void write() throws FileNotFoundException, IOException {
    FileOutputStream out = new FileOutputStream(new File(filename));
    Workbook wb;/*from  ww  w  .  j  a va 2 s  . co m*/

    wb = new XSSFWorkbook();

    Map<String, CellStyle> styles = createStyles(wb);
    Sheet sheet = wb.createSheet(sheetName);

    //turn off gridlines
    sheet.setDisplayGridlines(false);
    sheet.setPrintGridlines(false);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);

    sheet.setAutobreaks(true);
    printSetup.setFitHeight((short) 1);
    printSetup.setFitWidth((short) 1);

    Row headerRow = sheet.createRow(0);
    headerRow.setHeightInPoints(12.75f);

    int[][] width = new int[titles.length][titles.length];

    for (int i = 0; i < titles.length; i++) {
        Cell cell = headerRow.createCell((short) i);
        cell.setCellValue(titles[i]);
        cell.setCellStyle(styles.get("header"));

        width[i][0] = titles[i].length();
    }

    Row row;
    Cell cell;
    int rownum = 1;

    for (int i = 0; i < data.length; i++, rownum++) {
        row = sheet.createRow(rownum);
        if (data[i] == null)
            continue;

        for (int j = 0; j < data[i].length; j++) {
            cell = row.createCell((short) j);
            if (data[i][j] == null)
                data[i][j] = "";

            cell.setCellValue(data[i][j].toString());

            if (data[i][j].toString().length() > width[j][0])
                width[j][0] = data[i][j].toString().length();
        }
    }

    for (short i = 0; i < titles.length; i++) {
        short widthShort = (short) (256 * (width[i][0] + 3));

        sheet.setColumnWidth(i, widthShort);
    }

    int position = (titles.length / 2) - 1;

    row = sheet.createRow(rownum + 3);
    cell = row.createCell((short) position);

    if (footName == null) {
        SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm");
        cell.setCellValue("Export MaklerPoint vom " + df.format(new Date(System.currentTimeMillis()))
                + " - www.maklerpoint.de");
    } else {
        cell.setCellValue(footName);
    }

    sheet.setZoom(3, 4);

    wb.write(out);
    out.close();
}

From source file:de.thb.ue.backend.util.EvaluationExcelFileGenerator.java

License:Apache License

private void createTextualAnswers(@NonNull List<Vote> answers, @NonNull List<String> questionTexts, Sheet sheet,
        Workbook wb) {//from   w w  w  .  j a v  a2  s  .  c  o m
    Row row;
    Cell cell;
    row = sheet.createRow(sheet.getLastRowNum() + 2);
    cell = row.createCell(1);
    CellStyle helpStyle = wb.createCellStyle();
    helpStyle.cloneStyleFrom(headerStyle);
    helpStyle.setBorderBottom(CellStyle.BORDER_NONE);
    helpStyle.setBorderTop(CellStyle.BORDER_NONE);
    helpStyle.setBorderLeft(CellStyle.BORDER_NONE);
    helpStyle.setBorderRight(CellStyle.BORDER_NONE);
    cell.setCellValue("Kommentare");
    cell.setCellStyle(helpStyle);

    //TODO used to determine style for current line -> its stupid. Think of something better
    int styleCounter = 0;
    for (String textualQuestion : questionTexts) {
        row = sheet.createRow(sheet.getLastRowNum() + 3);
        cell = row.createCell(1);
        cell.setCellValue(textualQuestion);
        setTextQuestionStyle(cell, styleCounter, true);

        //colorize horizontal neighbour cells of headline
        for (int i = 2; i < 5; i++) {
            cell = row.createCell(i);
            setTextQuestionStyle(cell, styleCounter, false);
        }

        int rowNum = sheet.getLastRowNum();
        int counter = 1;

        for (String comment : aggregateTextAnswers(answers, textualQuestion)) {
            row = sheet.createRow(rowNum + 1);
            cell = row.createCell(1, Cell.CELL_TYPE_STRING);

            //              introduces line breaks in long comments
            ArrayList<String> commentChunks = splitComment(comment);
            StringBuilder formattedComment = new StringBuilder();
            formattedComment.append(Integer.toString(counter));
            formattedComment.append(": ");

            int chunkCounter = 0;
            for (String chunk : commentChunks) {
                formattedComment.append(chunk);

                if ((chunkCounter + 1) < commentChunks.size()) {
                    formattedComment.append(System.lineSeparator());
                }
                chunkCounter++;
            }
            cell.setCellValue(formattedComment.toString());

            CellStyle style = setTextQuestionStyle(cell, styleCounter, false);

            // increase height of row based on font size, number of lines and line spacing
            // the origin of 140 % -> http://superuser.com/questions/337181/how-many-pts-is-1-5-line-spacing-in-microsoft-word-2007
            float pointsPerLine = (wb.getFontAt(style.getFontIndex()).getFontHeightInPoints() * 140) / 100;
            row.setHeightInPoints(pointsPerLine * commentChunks.size());

            //colorize horizontal neighbour cells of comment
            for (int i = 2; i < 17; i++) {
                cell = row.createCell(i);
                setTextQuestionStyle(cell, styleCounter, false);
            }
            sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), 1, 17));

            rowNum++;
            counter++;
        }
        styleCounter++;
    }
}

From source file:demo.poi.BusinessPlan.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb = new HSSFWorkbook();

    Map<String, CellStyle> styles = createStyles(wb);

    Sheet sheet = wb.createSheet("Business Plan");

    // turn off gridlines
    sheet.setDisplayGridlines(false);/* w  w w. j a v a 2  s  .  c  o m*/
    sheet.setPrintGridlines(false);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);

    // the following three statements are required only for HSSF
    sheet.setAutobreaks(true);
    printSetup.setFitHeight((short) 1);
    printSetup.setFitWidth((short) 1);

    // the header row: centered text in 48pt font
    Row headerRow = sheet.createRow(0);
    headerRow.setHeightInPoints(12.75f);
    for (int i = 0; i < titles.length; i++) {
        Cell cell = headerRow.createCell(i);
        cell.setCellValue(titles[i]);
        cell.setCellStyle(styles.get("header"));
    }
    // columns for 11 weeks starting from 9-Jul
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);

    calendar.setTime(fmt.parse("9-Jul"));
    calendar.set(Calendar.YEAR, year);
    for (int i = 0; i < 11; i++) {
        Cell cell = headerRow.createCell(titles.length + i);
        cell.setCellValue(calendar);
        cell.setCellStyle(styles.get("header_date"));
        calendar.roll(Calendar.WEEK_OF_YEAR, true);
    }
    // freeze the first row
    sheet.createFreezePane(0, 1);

    Row row;
    Cell cell;
    int rownum = 1;
    for (int i = 0; i < data.length; i++, rownum++) {
        row = sheet.createRow(rownum);
        if (data[i] == null)
            continue;

        for (int j = 0; j < data[i].length; j++) {
            String str = data[i][j];
            cell = row.createCell(j);
            String styleName;
            boolean isHeader = i == 0 || data[i - 1] == null;
            switch (j) {
            case 0:
                if (isHeader) {
                    styleName = "cell_b";
                    cell.setCellValue(Double.parseDouble(data[i][j]));
                } else {
                    styleName = "cell_normal";
                    cell.setCellValue(data[i][j]);
                }
                break;
            case 1:
                if (isHeader) {
                    styleName = i == 0 ? "cell_h" : "cell_bb";
                } else {
                    styleName = "cell_indented";
                }
                cell.setCellValue(data[i][j]);
                break;
            case 2:
                styleName = isHeader ? "cell_b" : "cell_normal";
                cell.setCellValue(data[i][j]);
                break;
            case 3:
                styleName = isHeader ? "cell_b_centered" : "cell_normal_centered";
                cell.setCellValue(Integer.parseInt(data[i][j]));
                break;
            case 4: {
                calendar.setTime(fmt.parse(data[i][j]));
                calendar.set(Calendar.YEAR, year);
                cell.setCellValue(calendar);
                styleName = isHeader ? "cell_b_date" : "cell_normal_date";
                break;
            }
            case 5: {
                int r = rownum + 1;
                String fmla = "IF(AND(D" + r + ",E" + r + "),E" + r + "+D" + r + ",\"\")";
                cell.setCellFormula(fmla);
                styleName = isHeader ? "cell_bg" : "cell_g";
                break;
            }
            default:
                styleName = data[i][j] != null ? "cell_blue" : "cell_normal";
            }

            cell.setCellStyle(styles.get(styleName));
        }
    }

    // group rows for each phase, row numbers are 0-based
    sheet.groupRow(4, 6);
    sheet.groupRow(9, 13);
    sheet.groupRow(16, 18);

    // set column widths, the width is measured in units of 1/256th of a
    // character width
    sheet.setColumnWidth(0, 256 * 6);
    sheet.setColumnWidth(1, 256 * 33);
    sheet.setColumnWidth(2, 256 * 20);
    sheet.setZoom(3, 4);

    // Write the output to a file
    String file = "target/businessplan.xls";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}