Example usage for org.apache.poi.hssf.usermodel HSSFSheet createDrawingPatriarch

List of usage examples for org.apache.poi.hssf.usermodel HSSFSheet createDrawingPatriarch

Introduction

In this page you can find the example usage for org.apache.poi.hssf.usermodel HSSFSheet createDrawingPatriarch.

Prototype

@Override
public HSSFPatriarch createDrawingPatriarch() 

Source Link

Document

Creates the top-level drawing patriarch.

Usage

From source file:gov.nih.nci.cananolab.service.sample.impl.CompositionExporter.java

License:BSD License

/**
 * Output NanomaterialEntities data => bodyNanomaterialEntitySummaryView.jsp
 *
 * @param compBean//from   w  w  w .  jav  a2 s  . c  o m
 * @param wb
 * @param headerStyle
 * @param entityCount
 */
private static int outputNanomaterialEntities(CompositionBean compBean, HSSFWorkbook wb,
        HSSFCellStyle headerStyle, HSSFCellStyle hlinkStyle, int entityCount, String downloadURL) {
    List<NanomaterialEntityBean> nanoList = compBean.getNanomaterialEntities();
    if (nanoList != null && !nanoList.isEmpty()) {
        StringBuilder sb = new StringBuilder();
        for (NanomaterialEntityBean nanoEntity : nanoList) {
            if (!StringUtils.isEmpty(nanoEntity.getType())) {
                int rowIndex = 0;
                sb.setLength(0);
                sb.append(entityCount++).append('.').append(nanoEntity.getType());

                // Create one work sheet for each Nanomaterial Entity.
                HSSFSheet sheet = wb.createSheet(sb.toString());
                HSSFPatriarch patriarch = sheet.createDrawingPatriarch();

                // 1. Output Header: NanoMaterial at (0, 0), Composition
                // Type at (2, 0).
                rowIndex = outputHeader(CompositionBean.NANOMATERIAL_SELECTION, nanoEntity.getType(), sheet,
                        headerStyle, rowIndex);

                // 2. Output Composition Description at (4, 0).
                String description = nanoEntity.getEmulsion().getDescription();
                if (!StringUtils.isEmpty(description)) {
                    HSSFRow row = sheet.createRow(rowIndex++);
                    ExportUtils.createCell(row, 0, headerStyle, "Description");
                    ExportUtils.createCell(row, 1, description);
                }

                // 3. Output Composition Properties: 7x)
                // "nanomaterialEntity/*.jsp"
                if (nanoEntity.isWithProperties()) {
                    if (!StringUtils.isEmpty(description)) {
                        rowIndex++; // Create one empty line as separator.
                    }
                    HSSFRow row = sheet.createRow(rowIndex++);
                    ExportUtils.createCell(row, 0, headerStyle, "Properties");

                    NanomaterialEntity domainEntity = nanoEntity.getDomainEntity();
                    if (domainEntity instanceof Biopolymer) {
                        rowIndex = outputNanoProperties((Biopolymer) domainEntity, sheet, headerStyle,
                                rowIndex);
                    } else if (domainEntity instanceof Dendrimer) {
                        rowIndex = outputNanoProperties((Dendrimer) domainEntity, sheet, headerStyle, rowIndex);
                    } else if (domainEntity instanceof CarbonNanotube) {
                        rowIndex = outputNanoProperties((CarbonNanotube) domainEntity, sheet, headerStyle,
                                rowIndex);
                    } else if (domainEntity instanceof Liposome) {
                        rowIndex = outputNanoProperties((Liposome) domainEntity, sheet, headerStyle, rowIndex);
                    } else if (domainEntity instanceof Emulsion) {
                        rowIndex = outputNanoProperties((Emulsion) domainEntity, sheet, headerStyle, rowIndex);
                    } else if (domainEntity instanceof Polymer) {
                        rowIndex = outputNanoProperties((Polymer) domainEntity, sheet, headerStyle, rowIndex);
                    } else if (domainEntity instanceof Fullerene) {
                        rowIndex = outputNanoProperties((Fullerene) domainEntity, sheet, headerStyle, rowIndex);
                    }
                    rowIndex++; // Create one empty line as separator.
                }

                // 3. Output Composing Elements:
                // bodyComposingElementView.jsp
                List<ComposingElementBean> compElementBeans = nanoEntity.getComposingElements();
                if (compElementBeans != null && !compElementBeans.isEmpty()) {
                    HSSFRow row = sheet.createRow(rowIndex++);
                    ExportUtils.createCell(row, 0, headerStyle, "Composing Elements");

                    row = sheet.createRow(rowIndex++);
                    ExportUtils.createCell(row, 0, headerStyle, "Type");
                    ExportUtils.createCell(row, 1, headerStyle, "PubChem ID");
                    ExportUtils.createCell(row, 2, headerStyle, "Name");
                    ExportUtils.createCell(row, 3, headerStyle, "Amount");
                    ExportUtils.createCell(row, 4, headerStyle, "Molecular Formula");
                    ExportUtils.createCell(row, 5, headerStyle, "Function");
                    ExportUtils.createCell(row, 6, headerStyle, "Description");
                    for (ComposingElementBean compElementBean : compElementBeans) {
                        row = sheet.createRow(rowIndex++);
                        ComposingElement compElement = compElementBean.getDomain();
                        ExportUtils.createCell(row, 0, compElement.getType());

                        if (compElement.getPubChemId() != null) {
                            Long pubChemId = compElement.getPubChemId();
                            String pubChemDs = compElement.getPubChemDataSourceName();
                            sb.setLength(0);
                            sb.append(pubChemId).append(' ');
                            sb.append('(').append(pubChemDs).append(')');
                            ExportUtils.createCell(row, 1, hlinkStyle, sb.toString(),
                                    CompositionBean.getPubChemURL(pubChemDs, pubChemId));
                        }

                        ExportUtils.createCell(row, 2, compElement.getName());

                        sb.setLength(0);
                        sb.append(compElement.getValue()).append(' ');
                        sb.append(compElement.getValueUnit());
                        ExportUtils.createCell(row, 3, sb.toString());

                        if (!StringUtils.isEmpty(compElementBean.getMolecularFormulaDisplayName())) {
                            ExportUtils.createCell(row, 4, compElementBean.getMolecularFormulaDisplayName());
                        }

                        String[] funcNames = compElementBean.getFunctionDisplayNames();
                        if (funcNames != null && funcNames.length > 0) {
                            sb.setLength(0);
                            for (String funcName : funcNames) {
                                sb.append(',').append(' ').append(funcName);
                            }
                            ExportUtils.createCell(row, 5, sb.substring(2));
                        }

                        if (!StringUtils.isEmpty(compElement.getDescription())) {
                            ExportUtils.createCell(row, 6, compElement.getDescription());
                        }
                    }
                    rowIndex++; // Create one empty line as separator.
                } // 3. End of outputting Composing Elements.

                // Output Files: bodyFileView.jsp
                List<FileBean> fileBeans = nanoEntity.getFiles();
                if (fileBeans != null && !fileBeans.isEmpty()) {
                    rowIndex++; // Create one empty line as separator.
                    HSSFRow row = sheet.createRow(rowIndex++);
                    ExportUtils.createCell(row, 0, headerStyle, "Files");
                    outputFiles(fileBeans, downloadURL, wb, sheet, headerStyle, hlinkStyle, patriarch,
                            rowIndex);
                }
            }
        } // End of iterating nanoList.
    }

    return entityCount;
}

From source file:module.siadap.domain.SiadapRootModule.java

License:Open Source License

private void populateSheet(HSSFSheet sheetToWriteTo, boolean considerQuotas, UnitSiadapWrapper unitToSearchIn,
        HSSFWorkbook wb, boolean shouldIncludeEndOfRole, boolean includeHarmonizationResponsibles,
        boolean shouldIncludeUniverse) {

    CreationHelper creationHelper = wb.getCreationHelper();

    // make the sheet fit the page
    PrintSetup ps = sheetToWriteTo.getPrintSetup();

    sheetToWriteTo.setAutobreaks(true);//from  w w w. jav  a2s.  c  o m

    ps.setFitHeight((short) 1);
    ps.setFitWidth((short) 1);

    /* ** styles ** */

    // CostCenter style
    HSSFFont costCenterFont = wb.createFont();
    costCenterFont.setColor(HSSFColor.DARK_BLUE.index);
    costCenterFont.setFontHeightInPoints((short) 12);
    costCenterFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    CellStyle costCenterStyle = wb.createCellStyle();
    costCenterStyle.setFont(costCenterFont);

    // make the Unit header style
    CellStyle unitHeaderStyle = wb.createCellStyle();
    unitHeaderStyle.setBorderBottom(CellStyle.BORDER_THIN);
    unitHeaderStyle.setBorderTop(CellStyle.BORDER_THIN);
    unitHeaderStyle.setBorderLeft(CellStyle.BORDER_THIN);
    unitHeaderStyle.setBorderRight(CellStyle.BORDER_THIN);
    unitHeaderStyle.setAlignment(CellStyle.ALIGN_CENTER);
    unitHeaderStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    HSSFFont headerFont = wb.createFont();
    headerFont.setFontHeightInPoints((short) 12);
    headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    headerFont.setItalic(true);
    unitHeaderStyle.setFont(headerFont);

    // make the default name style
    CellStyle defaultTextNameStyle = wb.createCellStyle();
    defaultTextNameStyle.setBorderLeft(CellStyle.BORDER_THIN);
    defaultTextNameStyle.setBorderRight(CellStyle.BORDER_THIN);
    defaultTextNameStyle.setBorderBottom(CellStyle.BORDER_NONE);
    defaultTextNameStyle.setBorderTop(CellStyle.BORDER_NONE);
    defaultTextNameStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    HSSFFont defaultFont = wb.createFont();
    defaultFont.setFontHeightInPoints((short) 11);
    defaultTextNameStyle.setFont(defaultFont);

    // make the last line name style
    CellStyle defaultTextNameLastStyle = wb.createCellStyle();
    defaultTextNameLastStyle.setBorderLeft(CellStyle.BORDER_THIN);
    defaultTextNameLastStyle.setBorderRight(CellStyle.BORDER_THIN);
    defaultTextNameLastStyle.setBorderBottom(CellStyle.BORDER_THIN);
    defaultTextNameLastStyle.setBorderTop(CellStyle.BORDER_NONE);
    defaultTextNameLastStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    defaultTextNameLastStyle.setFont(defaultFont);

    // make the default IST-ID last line style
    CellStyle defaultTextIstIdLastStyle = wb.createCellStyle();
    defaultTextIstIdLastStyle.setBorderLeft(CellStyle.BORDER_THIN);
    defaultTextIstIdLastStyle.setBorderBottom(CellStyle.BORDER_THIN);
    defaultTextIstIdLastStyle.setBorderTop(CellStyle.BORDER_NONE);
    defaultTextIstIdLastStyle.setBorderRight(CellStyle.BORDER_THIN);
    defaultTextIstIdLastStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    defaultTextIstIdLastStyle.setAlignment(CellStyle.ALIGN_CENTER);
    defaultTextIstIdLastStyle.setFont(defaultFont);

    // make the default IST-ID style
    CellStyle defaultTextIstIdStyle = wb.createCellStyle();
    defaultTextIstIdStyle.setBorderLeft(CellStyle.BORDER_THIN);
    defaultTextIstIdStyle.setBorderBottom(CellStyle.BORDER_NONE);
    defaultTextIstIdStyle.setBorderTop(CellStyle.BORDER_NONE);
    defaultTextIstIdStyle.setBorderRight(CellStyle.BORDER_THIN);
    defaultTextIstIdStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    defaultTextIstIdStyle.setAlignment(CellStyle.ALIGN_CENTER);
    defaultTextIstIdStyle.setFont(defaultFont);

    // header style

    // CellStyle headerStyle = wb.createCellStyle();
    // HSSFFont headerFont = wb.createFont();
    // headerFont.setFontName(HSSFFont.FONT_ARIAL);
    // headerFont.setFontHeightInPoints((short) 10);
    // headerStyle.setFont(headerFont);
    //

    // first line style
    CellStyle firstLineStyle = wb.createCellStyle();
    HSSFFont firstLineFont = wb.createFont();
    firstLineFont.setColor(HSSFColor.DARK_BLUE.index);
    firstLineFont.setFontHeightInPoints((short) 14);
    firstLineFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    firstLineStyle.setFont(firstLineFont);
    firstLineStyle.setAlignment(CellStyle.ALIGN_CENTER);
    firstLineStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);

    // second line style
    CellStyle secondLineStyle = wb.createCellStyle();
    HSSFFont secondLineFont = wb.createFont();
    secondLineFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    secondLineFont.setFontHeightInPoints((short) 14);
    secondLineStyle.setFont(secondLineFont);
    secondLineStyle.setAlignment(CellStyle.ALIGN_CENTER);
    secondLineStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);

    // the style for Unit Harmonization responsibles - title
    CellStyle unitHarmonizationTitleStyle = wb.createCellStyle();
    // the BLUE title font - is equal to 'firstLineFont'
    unitHarmonizationTitleStyle.setFont(firstLineFont);
    // now we just have to shade it
    unitHarmonizationTitleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    unitHarmonizationTitleStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    unitHarmonizationTitleStyle.setAlignment(CellStyle.ALIGN_CENTER);

    // the style for Unit Harmonization responsibles - normal

    // let's create the BLUE Arial 14 font for the responsibles of
    // harmonization
    HSSFFont harmonizationResponsibleFont = wb.createFont();
    harmonizationResponsibleFont.setColor(HSSFColor.DARK_BLUE.index);
    harmonizationResponsibleFont.setFontHeightInPoints((short) 14);

    CellStyle unitHarmonizationResponsibleStyle = wb.createCellStyle();
    unitHarmonizationResponsibleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    unitHarmonizationResponsibleStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    unitHarmonizationResponsibleStyle.setFont(harmonizationResponsibleFont);
    unitHarmonizationResponsibleStyle.setAlignment(CellStyle.ALIGN_CENTER);

    /* ** END of styles ** */

    /* ** Immutable IST header ** */

    HSSFHeader header = sheetToWriteTo.getHeader();
    header.setCenter(HSSFHeader.font("Arial", "Normal") + HSSFHeader.fontSize((short) 10));
    header.setCenter("Instituto Superior Tcnico");

    int rowIndex = START_ROW_INDEX;
    int cellIndex = START_CELL_INDEX;

    int firstLineIndex = rowIndex++;
    int secondLineIndex = rowIndex++;
    /* ** Write the first lines with the dates ** */
    HSSFRow row = sheetToWriteTo.createRow(firstLineIndex);
    HSSFCell cell = row.createCell(cellIndex);
    cell.setCellValue("SIADAP - LISTA DE AVALIADORES " + unitToSearchIn.getYear());
    cell.setCellStyle(firstLineStyle);
    sheetToWriteTo
            .addMergedRegion(new CellRangeAddress(firstLineIndex, firstLineIndex, cellIndex, cellIndex + 3));

    // second line
    if (!considerQuotas) {
        cellIndex = START_CELL_INDEX;
        row = sheetToWriteTo.createRow(secondLineIndex);
        cell = row.createCell(cellIndex);
        cell.setCellValue("PESSOAL CONTRATADO PELA ADIST");
        cell.setCellStyle(secondLineStyle);

    }

    /* ** write the IST logo ** */

    int pictureIdx = wb.addPicture(istLogoBytes, Workbook.PICTURE_TYPE_PNG);
    HSSFPatriarch drawingPatriarch = sheetToWriteTo.createDrawingPatriarch();
    ClientAnchor clientAnchor = creationHelper.createClientAnchor();
    clientAnchor.setCol1(cellIndex);
    clientAnchor.setRow1(rowIndex);
    HSSFPicture picture = drawingPatriarch.createPicture(clientAnchor, pictureIdx);

    // let's give the next item some space
    rowIndex += 6;

    /* ** Dynamic IST footer ** */

    HSSFFooter footer = sheetToWriteTo.getFooter();
    footer.setLeft("Lista gerada em: " + HSSFFooter.date() + " " + HSSFFooter.time());
    footer.setCenter(HSSFFooter.page());
    footer.setRight("SIADAP - Lista de avaliadores " + unitToSearchIn.getYear());

    for (UnitSiadapWrapper eachUnit : unitToSearchIn
            .getAllChildUnits(unitToSearchIn.getConfiguration().getUnitRelations())) {

        Collection<Person> harmonizationResponsibles = eachUnit.getHarmonizationResponsibles();
        if (includeHarmonizationResponsibles && !harmonizationResponsibles.isEmpty()) {
            // let's add the section stating the responsible for
            // Harmonization
            cellIndex = START_CELL_INDEX;
            row = sheetToWriteTo.createRow(++rowIndex);
            // let's merge the row
            sheetToWriteTo.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, cellIndex, cellIndex + 3));
            cell = row.createCell(cellIndex);
            cell.setCellStyle(unitHarmonizationTitleStyle);
            cell.setCellValue("UNIDADE DE HARMONIZAO: " + eachUnit.getName());
            // a 'blank' styled line
            row = sheetToWriteTo.createRow(++rowIndex);
            // merge it
            sheetToWriteTo.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, cellIndex, cellIndex + 3));
            row.createCell(cellIndex).setCellStyle(unitHarmonizationResponsibleStyle);
            // each responsible has one of the following lines
            for (Person harmonizationResponsible : harmonizationResponsibles) {
                cellIndex = START_CELL_INDEX;
                row = sheetToWriteTo.createRow(++rowIndex);
                // merge it
                sheetToWriteTo
                        .addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, cellIndex, cellIndex + 3));
                cell = row.createCell(cellIndex);
                cell.setCellStyle(unitHarmonizationResponsibleStyle);
                cell.setCellValue("RESPONS?VEL PELA HARMONIZAO: " + harmonizationResponsible.getName());
            }
            // and let's add an extra 'blank' styled line
            row = sheetToWriteTo.createRow(++rowIndex);
            sheetToWriteTo.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, cellIndex, cellIndex + 3));
            row.createCell(cellIndex).setCellStyle(unitHarmonizationResponsibleStyle);
            // and a regular one! (skip one in the index)
            ++rowIndex;

        }
        if (eachUnit.getQuotaAwareTotalPeopleWorkingInUnit(false, considerQuotas) > 0) {

            row = sheetToWriteTo.createRow(++rowIndex);
            cellIndex = START_CELL_INDEX;
            // write the unit name and cost center
            String unitNameWithCC = eachUnit.getUnit().getPartyName().getContent();
            if (eachUnit.getUnit().getPartyTypesSet().contains(PartyType.readBy("CostCenter"))) {
                unitNameWithCC += " - " + eachUnit.getUnit().getAcronym();
            }
            cell = row.createCell(cellIndex++);
            sheetToWriteTo.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, --cellIndex, ++cellIndex));
            cell.setCellValue(unitNameWithCC);
            cell.setCellStyle(costCenterStyle);

            /* **** write the Unit header ***** */

            // restart the cell's index
            cellIndex = START_CELL_INDEX;

            // IST id avaliado
            int firstLineAfterUnitNameIndex = ++rowIndex;
            int secondLineAfterUnitNameIndex = ++rowIndex;

            row = sheetToWriteTo.createRow(firstLineAfterUnitNameIndex);
            cell = row.createCell(cellIndex);
            cell.setCellStyle(unitHeaderStyle);
            cell.setCellValue("IST id.");

            row = sheetToWriteTo.createRow(secondLineAfterUnitNameIndex);
            cell = row.createCell(cellIndex);
            cell.setCellStyle(unitHeaderStyle);

            // merge the IST id
            sheetToWriteTo.addMergedRegion(new CellRangeAddress(firstLineAfterUnitNameIndex,
                    secondLineAfterUnitNameIndex, cellIndex, cellIndex));

            // Nome avaliado
            row = sheetToWriteTo.getRow(firstLineAfterUnitNameIndex);
            cell = row.createCell(++cellIndex);
            cell.setCellStyle(unitHeaderStyle);
            cell.setCellValue("Nome");

            row = sheetToWriteTo.getRow(secondLineAfterUnitNameIndex);
            cell = row.createCell(cellIndex);
            cell.setCellStyle(unitHeaderStyle);

            // merge
            sheetToWriteTo.addMergedRegion(new CellRangeAddress(firstLineAfterUnitNameIndex,
                    secondLineAfterUnitNameIndex, cellIndex, cellIndex));

            if (shouldIncludeUniverse) {

                // SIADAP do avaliado
                row = sheetToWriteTo.getRow(firstLineAfterUnitNameIndex);
                cell = row.createCell(++cellIndex);
                cell.setCellStyle(unitHeaderStyle);
                cell.setCellValue("SIADAP");

                row = sheetToWriteTo.getRow(secondLineAfterUnitNameIndex);
                cell = row.createCell(cellIndex);
                cell.setCellStyle(unitHeaderStyle);

                // merge
                sheetToWriteTo.addMergedRegion(new CellRangeAddress(firstLineAfterUnitNameIndex,
                        secondLineAfterUnitNameIndex, cellIndex, cellIndex));
            }

            // Ist id do avaliador
            row = sheetToWriteTo.getRow(firstLineAfterUnitNameIndex);
            cell = row.createCell(++cellIndex);
            cell.setCellStyle(unitHeaderStyle);
            cell.setCellValue("IST id.");

            row = sheetToWriteTo.getRow(secondLineAfterUnitNameIndex);
            cell = row.createCell(cellIndex);
            cell.setCellStyle(unitHeaderStyle);

            // merge
            sheetToWriteTo.addMergedRegion(new CellRangeAddress(firstLineAfterUnitNameIndex,
                    secondLineAfterUnitNameIndex, cellIndex, cellIndex));

            // avaliador
            row = sheetToWriteTo.getRow(firstLineAfterUnitNameIndex);
            cell = row.createCell(++cellIndex);
            cell.setCellStyle(unitHeaderStyle);
            cell.setCellValue("Avaliador");

            row = sheetToWriteTo.getRow(secondLineAfterUnitNameIndex);
            cell = row.createCell(cellIndex);
            cell.setCellStyle(unitHeaderStyle);

            // merge
            sheetToWriteTo.addMergedRegion(new CellRangeAddress(firstLineAfterUnitNameIndex,
                    secondLineAfterUnitNameIndex, cellIndex, cellIndex));

            List<PersonSiadapWrapper> listToUse = (considerQuotas) ? eachUnit.getUnitEmployeesWithQuotas(false)
                    : eachUnit.getUnitEmployeesWithoutQuotas(true);

            // now let's take care of exporting the persons
            for (PersonSiadapWrapper personWrapper : listToUse) {
                row = sheetToWriteTo.createRow(++rowIndex);
                // restart the cell's index
                cellIndex = START_CELL_INDEX;
                String istIdEvaluated = personWrapper.getPerson().getUser().getUsername();
                cell = row.createCell(cellIndex++);
                cell.setCellValue(istIdEvaluated);
                cell.setCellStyle(defaultTextIstIdStyle);

                String nameEvaluatedPerson = personWrapper.getPerson().getName();
                cell = row.createCell(cellIndex++);
                cell.setCellValue(nameEvaluatedPerson);
                cell.setCellStyle(defaultTextNameStyle);

                if (shouldIncludeUniverse) {

                    Siadap siadap = personWrapper.getSiadap();
                    String siadapUniverseToBeWritten = (siadap == null
                            || siadap.getDefaultSiadapUniverse() == null) ? "No definido"
                                    : siadap.getDefaultSiadapUniverse().getLocalizedName();
                    cell = row.createCell(cellIndex++);
                    cell.setCellValue(siadapUniverseToBeWritten);
                    cell.setCellStyle(defaultTextNameStyle);
                }

                PersonSiadapWrapper evaluatorWrapper = personWrapper.getEvaluator();
                String istIdEvaluator = evaluatorWrapper == null ? "-"
                        : evaluatorWrapper.getPerson().getUser().getUsername();
                cell = row.createCell(cellIndex++);
                cell.setCellValue(istIdEvaluator);
                cell.setCellStyle(defaultTextIstIdStyle);

                String nameEvaluatorWrapper = evaluatorWrapper == null ? "-" : evaluatorWrapper.getName();
                cell = row.createCell(cellIndex++);
                cell.setCellValue(nameEvaluatorWrapper);
                cell.setCellStyle(defaultTextNameStyle);

            }
            // let's make a bottom border on the last four cells
            for (int i = START_CELL_INDEX; i < START_CELL_INDEX + 4; i++) {
                cell = row.getCell(i);
                // let's diferentaitate between the IST-id and the name
                if (i == START_CELL_INDEX || i == START_CELL_INDEX + 2) // first
                // cell,
                // IST-ID
                // then.
                // or
                // third
                // cell
                // the
                // other
                // IST-ID
                {
                    cell.setCellStyle(defaultTextIstIdLastStyle);
                } else {
                    cell.setCellStyle(defaultTextNameLastStyle);
                }

            }
            row = sheetToWriteTo.createRow(++rowIndex);
            row = sheetToWriteTo.createRow(++rowIndex);

        }

    }

    sheetToWriteTo.autoSizeColumn(START_CELL_INDEX);
    sheetToWriteTo.autoSizeColumn(START_CELL_INDEX + 1);
    sheetToWriteTo.autoSizeColumn(START_CELL_INDEX + 2);
    sheetToWriteTo.autoSizeColumn(START_CELL_INDEX + 3);
    sheetToWriteTo.autoSizeColumn(START_CELL_INDEX + 4);

    // now let's resize the logo
    picture.resize();
}

From source file:mx.avanti.siract.ui.FiltrosBeanUI.java

public HSSFSheet cabezeraGeneralExcel(HSSFSheet sheet, int logouabc, HSSFCellStyle style) {
    /* Create the drawing container */
    HSSFPatriarch drawing = sheet.createDrawingPatriarch();
    /* Create an anchor point */
    ClientAnchor my_anchor = new HSSFClientAnchor();
    /* Define top left corner, and we can resize picture suitable from there */
    my_anchor.setCol1(1);//from  ww w. j av  a 2  s  . co  m
    my_anchor.setRow1(1);
    /* Invoke createPicture and pass the anchor point and ID */
    HSSFPicture my_picture = drawing.createPicture(my_anchor, logouabc);
    /* Call resize method, which resizes the image */
    double escalaRes = 1;
    my_picture.resize(escalaRes);
    //definiremos el estilo para estas Celdas
    //Definiremos el nombre de la escuela
    HSSFRow row = sheet.createRow(2);
    row.setHeight((short) 600);
    HSSFCell cell = row.createCell(3);
    cell.setCellValue("Universidad Autnoma de Baja California");
    cell.setCellStyle(style);
    row = sheet.createRow(3);
    row.setHeight((short) 600);
    cell = row.createCell(3);
    cell.setCellValue("Facultad de Ingeniera");
    cell.setCellStyle(style);
    row = sheet.createRow(4);
    row.setHeight((short) 600);
    cell = row.createCell(3);
    cell.setCellValue("Mexicali");
    cell.setCellStyle(style);
    return sheet;
}

From source file:net.ceos.project.poi.annotated.core.CellStyleHandler.java

License:Apache License

/**
 * Apply the cell comment to a cell.//from ww w  . j  a v  a  2 s  .co  m
 * 
 * @param configCriteria
 *            the {@link XConfigCriteria} object
 * @param isAuthorizedComment
 *            the extension file
 * @param cell
 *            the {@link Cell}
 */
protected static void applyComment(final XConfigCriteria configCriteria, final Boolean isAuthorizedComment,
        final Cell cell) {
    if (StringUtils.isBlank(configCriteria.getElement().commentRules())
            || StringUtils.isNotBlank(configCriteria.getElement().commentRules()) && isAuthorizedComment) {
        if (ExtensionFileType.XLS.equals(configCriteria.getExtension())) {
            final Map<Sheet, HSSFPatriarch> drawingPatriarches = new HashMap<>();

            CreationHelper createHelper = cell.getSheet().getWorkbook().getCreationHelper();
            HSSFSheet sheet = (HSSFSheet) cell.getSheet();
            HSSFPatriarch drawingPatriarch = drawingPatriarches.get(sheet);
            if (drawingPatriarch == null) {
                drawingPatriarch = sheet.createDrawingPatriarch();
                drawingPatriarches.put(sheet, drawingPatriarch);
            }

            Comment comment = drawingPatriarch
                    .createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
            comment.setString(createHelper.createRichTextString(configCriteria.getElement().comment()));

            cell.setCellComment(comment);

        } else if (ExtensionFileType.XLSX.equals(configCriteria.getExtension())) {
            CreationHelper factory = configCriteria.getWorkbook().getCreationHelper();

            Drawing drawing = cell.getSheet().createDrawingPatriarch();

            ClientAnchor anchor = factory.createClientAnchor();

            Comment comment = drawing.createCellComment(anchor);
            RichTextString str = factory.createRichTextString(configCriteria.getElement().comment());
            comment.setString(str);

            cell.setCellComment(comment);
        }
    }
}

From source file:org.bbreak.excella.core.handler.DebugErrorHandler.java

License:Open Source License

/**
 * ?/*from ww w.j a  v a2  s .  co  m*/
 * 
 * @param workbook 
 * @param errorCell
 * @param exception
 */
protected void markupErrorCell(Workbook workbook, ParseException exception) {
    Cell errorCell = exception.getCell();
    if (errorCell == null) {
        return;
    }
    // ????
    workbook.setActiveSheet(workbook.getSheetIndex(errorCell.getSheet()));
    errorCell.setAsActiveCell();

    if (workbook instanceof XSSFWorkbook) {
        XSSFWorkbook xssfWorkbook = (XSSFWorkbook) workbook;

        CellStyle errorCellStyle = xssfWorkbook.createCellStyle();
        errorCellStyle.setFillForegroundColor(HSSFColorPredefined.ROSE.getIndex());
        errorCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        errorCell.setCellStyle(errorCellStyle);

        // TODO:???????????????
        // XSSFComment xssfComment = ((XSSFSheet)sheet).createComment();
        // xssfComment.setRow( errorCell.getRowIndex());
        // xssfComment.setColumn( (short)errorCell.getColumnIndex());
        // XSSFRichTextString string = new XSSFRichTextString( ex.getMessage());
        // xssfComment.setString( ex.getMessage());
    } else {
        HSSFWorkbook hssfWorkbook = (HSSFWorkbook) workbook;
        int sheetNum = hssfWorkbook.getNumberOfSheets();
        for (int cnt = 0; cnt < sheetNum; cnt++) {
            hssfWorkbook.getSheetAt(cnt).setSelected(false);
        }

        // ?
        CellStyle errorCellStyle = hssfWorkbook.createCellStyle();
        errorCellStyle.setFillForegroundColor(HSSFColorPredefined.ROSE.getIndex());
        errorCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        errorCell.setCellStyle(errorCellStyle);

        // ?
        short commentColFrom = (short) (errorCell.getColumnIndex() + 1);
        short commentColTo = (short) (errorCell.getColumnIndex() + ERROR_COMENT_COL_SIZE);
        int commentRowFrom = errorCell.getRowIndex();
        int commentRowTo = errorCell.getRowIndex() + ERROR_COMENT_ROW_SIZE;

        HSSFSheet hssfSheet = (HSSFSheet) errorCell.getSheet();
        HSSFPatriarch patr = hssfSheet.createDrawingPatriarch();
        hssfSheet.setSelected(true);
        HSSFComment comment = patr.createComment(
                new HSSFClientAnchor(0, 0, 0, 0, commentColFrom, commentRowFrom, commentColTo, commentRowTo));
        comment.setVisible(true);
        comment.setString(new HSSFRichTextString(createCommentMessage(exception)));
        errorCell.setCellComment(comment);
    }
}

From source file:org.jfree.chart.demo.LineChartDemo1.java

License:Open Source License

public void addChartToExcel(JFreeChart chart, HSSFWorkbook wb) throws Exception {
    final BufferedImage buffer = chart.createBufferedImage(WIDTH, HIGH);
    //final FileOutputStream file = new FileOutputStream(excel+".xls");

    ByteArrayOutputStream img_bytes = new ByteArrayOutputStream();
    ImageIO.write(buffer, "png", img_bytes);
    img_bytes.flush();//from  w  w  w  .  j ava  2s .  co  m
    /*Esta es la parte para agregar todo lo gneraod al excel*/
    /*Esta es la parte para agregar todo lo gneraod al excel*/
    /*Esta es la parte para agregar todo lo gneraod al excel*/
    //HSSFWorkbook wb = new HSSFWorkbook();
    //wb.createSheet(SHEET_NAME);
    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) POSITION_X, POSITION_Y,
            (short) CHART_WIDTH, CHART_HIGH);
    int index = wb.addPicture(img_bytes.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG);
    HSSFSheet sheet = wb.getSheet(SHEET_NAME);
    HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
    patriarch.createPicture(anchor, index);
    //wb.write(file);
    //file.close();
}

From source file:org.jxstar.report.util.ReportXlsUtil.java

/**
 * ???1SHEET1SHEET/*  w  w w .j av a2s .c o  m*/
 * 
 * @param destBook -- 
 * @param srcBook -- ??
 */
private static void copySheetImage(HSSFWorkbook destBook, HSSFWorkbook srcBook) {
    //???
    HSSFSheet srcSheet = srcBook.getSheetAt(0);
    //?
    HSSFSheet destSheet = destBook.getSheetAt(0);

    //???
    int endRowNum = destSheet.getPhysicalNumberOfRows();

    //????
    List<HSSFPicture> lsSrcPicture = getAllPicture(srcSheet);
    _log.showDebug("----------source picture size:" + lsSrcPicture.size());
    if (lsSrcPicture.isEmpty())
        return;

    //?????
    List<HSSFPictureData> lsPicData = null;
    try {
        lsPicData = srcBook.getAllPictures();
    } catch (Exception e) {
        _log.showWarn(
                "book?getAllPictures?book??");

        HSSFWorkbook tmpBook = copyWorkbook(srcBook);
        if (tmpBook != null) {
            lsPicData = tmpBook.getAllPictures();
            tmpBook = null;
        }
        /* ????
        //???
        lsPicData = destBook.getAllPictures();
        if (lsPicData == null || lsPicData.isEmpty()) return;
                
        //??1?
        List<HSSFPictureData> destData = FactoryUtil.newList();
        for (int i = 0, n = lsSrcPicture.size(); i < n; i++) {
           destData.add(lsPicData.get(0));
        }
        lsPicData = destData;*/
    }
    if (lsPicData == null || lsPicData.isEmpty())
        return;
    _log.showDebug("----------source data size:" + lsPicData.size());

    //????
    //????sheet???book
    if (lsSrcPicture.size() > lsPicData.size()) {
        _log.showWarn("?????");
        return;
    }

    //??
    HSSFPatriarch destDraw = destSheet.getDrawingPatriarch();
    if (destDraw == null) {
        destDraw = destSheet.createDrawingPatriarch();
    }

    //??
    List<HSSFPicture> lsDestPicture = getAllPicture(destSheet);
    int index = lsDestPicture.size();

    for (int i = 0, n = lsSrcPicture.size(); i < n; i++) {
        //?
        HSSFPicture picture = lsSrcPicture.get(i);
        //?????
        HSSFPictureData picdata = lsPicData.get(i);
        //??
        byte[] datas = picdata.getData();

        //???
        HSSFClientAnchor anchor = (HSSFClientAnchor) picture.getAnchor();

        //??
        anchor.setRow1(anchor.getRow1() + endRowNum);
        anchor.setRow2(anchor.getRow2() + endRowNum);

        //???
        destBook.addPicture(datas, picdata.getFormat());
        //???????+1??
        index++;
        _log.showDebug("---------copy new image index=" + index);

        destDraw.createPicture(anchor, index);
    }
}

From source file:org.jxstar.report.util.ReportXlsUtil.java

/**
 * ??POI?ReportImageUtil/*  w w w .  j  a v  a2  s .c  o m*/
 * @param cell -- ?
 * @param bytes -- 
 */
public static void addImageToSheet(HSSFCell cell, byte[] bytes) {
    if (cell == null) {
        _log.showError("-----insertImageToSheet: cell is null!");
        return;
    }
    if (bytes == null || bytes.length == 0) {
        _log.showError("-----insertImageToSheet: bytes is null!");
        return;
    }

    //??
    HSSFSheet sheet = cell.getSheet();

    //?
    int firstRow = cell.getRowIndex();
    int lastRow = cell.getRowIndex();
    int firstCol = cell.getColumnIndex();
    int lastCol = cell.getColumnIndex();
    //??
    CellRangeAddress range = getMergedRegion(cell);
    if (range != null) {
        firstRow = range.getFirstRow();
        lastRow = range.getLastRow();
        firstCol = range.getFirstColumn();
        lastCol = range.getLastColumn();
    }
    _log.showDebug("---------image cells=[" + firstRow + "," + firstCol + "," + lastRow + "," + lastCol + "]");
    //????5??1023255
    HSSFClientAnchor anchor = new HSSFClientAnchor(10, 5, 1013, 250, (short) firstCol, firstRow,
            (short) lastCol, lastRow);
    anchor.setAnchorType(HSSFClientAnchor.MOVE_AND_RESIZE);

    //??
    HSSFPatriarch draw = sheet.getDrawingPatriarch();
    if (draw == null) {
        draw = sheet.createDrawingPatriarch();
    }

    //???
    sheet.getWorkbook().addPicture(bytes, HSSFWorkbook.PICTURE_TYPE_JPEG);

    //???????+1??
    List<HSSFPicture> lsPicture = getAllPicture(sheet);
    int index = lsPicture.size() + 1;
    _log.showDebug("---------new image index=" + index);

    draw.createPicture(anchor, index);
}

From source file:org.unitime.timetable.export.XLSPrinter.java

License:Apache License

protected void addImageToSheet(int colNumber, int rowNumber, HSSFSheet sheet, BufferedImage image,
        double reqImageWidthMM, double reqImageHeightMM, int resizeBehaviour) throws IOException {
    ClientAnchorDetail colClientAnchorDetail = fitImageToColumns(sheet, colNumber, reqImageWidthMM,
            resizeBehaviour);/*from   www  .  j a va 2s . c o m*/
    ClientAnchorDetail rowClientAnchorDetail = fitImageToRows(sheet, rowNumber, reqImageHeightMM,
            resizeBehaviour);

    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, colClientAnchorDetail.getInset(),
            rowClientAnchorDetail.getInset(), (short) colClientAnchorDetail.getFromIndex(),
            rowClientAnchorDetail.getFromIndex(), (short) colClientAnchorDetail.getToIndex(),
            rowClientAnchorDetail.getToIndex());

    anchor.setAnchorType(AnchorType.MOVE_AND_RESIZE);

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    ImageIO.write(image, "PNG", bytes);

    int index = sheet.getWorkbook().addPicture(bytes.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG);

    HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
    patriarch.createPicture(anchor, index);
}

From source file:poi.hssf.usermodel.examples.AddDimensionedImage.java

License:Apache License

/**
 * Add an image to a worksheet.//from  www  . j av  a  2 s  .c  om
 *
 * @param colNumber A primitive int that contains the index number of a
 *                  column on the worksheet; POI column indices are zero
 *                  based. Together with the rowNumber parameter's value,
 *                  this parameter identifies a cell on the worksheet. The
 *                  image's top left hand corner will be aligned with the
 *                  top left hand corner of this cell.
 * @param rowNumber A primtive int that contains the index number of a row
 *                  on the worksheet; POI row indices are zero based.
 *                  Together with the rowNumber parameter's value, this
 *                  parameter identifies a cell on the worksheet. The
 *                  image's top left hand corner will be aligned with the
 *                  top left hand corner of this cell.
 * @param sheet A reference to the sheet that contains the cell identified
 *              by the two parameters above.
 * @param imageFile A String that encapsulates the name of and path to
 *                  the image that is to be 'inserted into' the sheet.
 * @param reqImageWidthMM A primitive double that contains the required
 *                        width of the image in millimetres.
 * @param reqImageHeightMM A primitive double that contains the required
 *                         height of the image in millimetres.
 * @param resizeBehaviour A primitive int whose value will determine how
 *                        the code should react if the image is larger than
 *                        the cell referenced by the colNumber and
 *                        rowNumber parameters. Four constants are provided
 *                        to determine what should happen;
 *                          AddDimensionedImage.EXPAND_ROW
 *                          AddDimensionedImage.EXPAND_COLUMN
 *                          AddDimensionedImage.EXPAND_ROW_AND_COLUMN
 *                          AddDimensionedImage.OVERLAY_ROW_AND_COLUMN
 * @throws java.io.FileNotFoundException If the file containing the image
 *                                       cannot be located.
 * @throws java.io.IOException If a problem occurs whilst reading the file
 *                             of image data.
 * @throws IllegalArgumentException If an invalid value is passed
 *                                            to the resizeBehaviour
 *                                            parameter.
 */
private void addImageToSheet(int colNumber, int rowNumber, HSSFSheet sheet, String imageFile,
        double reqImageWidthMM, double reqImageHeightMM, int resizeBehaviour)
        throws FileNotFoundException, IOException, IllegalArgumentException {
    HSSFRow row = null;
    HSSFClientAnchor anchor = null;
    HSSFPatriarch patriarch = null;
    ClientAnchorDetail rowClientAnchorDetail = null;
    ClientAnchorDetail colClientAnchorDetail = null;

    // Validate the resizeBehaviour parameter.
    if ((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN)
            && (resizeBehaviour != AddDimensionedImage.EXPAND_ROW)
            && (resizeBehaviour != AddDimensionedImage.EXPAND_ROW_AND_COLUMN)
            && (resizeBehaviour != AddDimensionedImage.OVERLAY_ROW_AND_COLUMN)) {
        throw new IllegalArgumentException("Invalid value passed to the "
                + "resizeBehaviour parameter of AddDimensionedImage.addImageToSheet()");
    }

    // Call methods to calculate how the image and sheet should be
    // manipulated to accomodate the image; columns and then rows.
    colClientAnchorDetail = this.fitImageToColumns(sheet, colNumber, reqImageWidthMM, resizeBehaviour);
    rowClientAnchorDetail = this.fitImageToRows(sheet, rowNumber, reqImageHeightMM, resizeBehaviour);

    // Having determined if and how to resize the rows, columns and/or the
    // image, create the HSSFClientAnchor object to position the image on
    // the worksheet. Note how the two ClientAnchorDetail records are
    // interrogated to recover the row/column co-ordinates and any insets.
    // The first two parameters are not used currently but could be if the
    // need arose to extend the functionality of this code by adding the
    // ability to specify that a clear 'border' be placed around the image.
    anchor = new HSSFClientAnchor(0, 0, colClientAnchorDetail.getInset(), rowClientAnchorDetail.getInset(),
            (short) colClientAnchorDetail.getFromIndex(), rowClientAnchorDetail.getFromIndex(),
            (short) colClientAnchorDetail.getToIndex(), rowClientAnchorDetail.getToIndex());

    // For now, set the anchor type to do not move or resize the
    // image as the size of the row/column is adjusted. This could easilly
    // become another parameter passed to the method.
    //anchor.setAnchorType(HSSFClientAnchor.DONT_MOVE_AND_RESIZE);
    anchor.setAnchorType(HSSFClientAnchor.MOVE_AND_RESIZE);

    // Now, add the picture to the workbook. Note that the type is assumed
    // to be a JPEG/JPG, this could easily (and should) be parameterised
    // however.
    //int index = sheet.getWorkbook().addPicture(this.imageToBytes(imageFile),
    //            HSSFWorkbook.PICTURE_TYPE_JPEG);
    int index = sheet.getWorkbook().addPicture(this.imageToBytes(imageFile), HSSFWorkbook.PICTURE_TYPE_PNG);

    // Get the drawing patriarch and create the picture.
    patriarch = sheet.createDrawingPatriarch();
    patriarch.createPicture(anchor, index);
}