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

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

Introduction

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

Prototype

int addPicture(byte[] pictureData, int format);

Source Link

Document

Adds a picture to the workbook.

Usage

From source file:it.eng.spagobi.engines.worksheet.exporter.WorkSheetXLSExporter.java

License:Mozilla Public License

public void setImageIntoWorkSheet(Workbook wb, Drawing drawing, File f, int col, int colend, int sheetRow,
        int height, int imgType) throws IOException {
    FileInputStream fis = new FileInputStream(f);

    ByteArrayOutputStream imgBytes = new ByteArrayOutputStream();
    int b;//  w w w . ja  va2 s .  co m
    while ((b = fis.read()) != -1) {
        imgBytes.write(b);
    }
    int dx1 = 0;
    int dy1 = 0;
    int dx2 = 0;
    int dy2 = 0;

    int index = wb.addPicture(imgBytes.toByteArray(), imgType);
    imgBytes.close();
    fis.close();

    ClientAnchor anchor = getClientAnchor(col, colend, sheetRow, height, dx1, dy1, dx2, dy2);
    drawing.createPicture(anchor, index);

}

From source file:jdbreport.model.io.xls.poi.Excel2003Writer.java

License:Apache License

private int createImage(Workbook wb, jdbreport.model.Cell cell, RenderedImage image) {

    String format = cell.getImageFormat();
    if (format != null && ("jpeg".equals(format.toLowerCase()) || "jpg".equals(format.toLowerCase()))) {
        format = "jpg";
    } else {//from w w  w . java  2 s.c  om
        format = "png";
    }

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    try {
        ImageIO.write(image, format, stream);
    } catch (IOException e) {
        e.printStackTrace();
    }
    byte[] bytes = stream.toByteArray();
    return wb.addPicture(bytes, "jpg".equals(format) ? Workbook.PICTURE_TYPE_JPEG : Workbook.PICTURE_TYPE_PNG);
}

From source file:nc.noumea.mairie.appock.services.impl.ExportExcelServiceImpl.java

License:Open Source License

private void insertPhotoArticleCatalogueInCell(Workbook wb, Sheet sheet, ArticleCatalogue articleCatalogue,
        int ligne, Row row, boolean mouvementStock) throws IOException {
    File fichierPhotoArticleCatalogue = catalogueService
            .getFilePieceJointe(articleCatalogue.getPhotoArticleCatalogue());
    byte[] bytes = Files.readAllBytes(fichierPhotoArticleCatalogue.toPath());
    int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
    Drawing drawing = sheet.createDrawingPatriarch();
    CreationHelper helper = wb.getCreationHelper();
    ClientAnchor anchor = helper.createClientAnchor();
    anchor.setCol1(10);//from w  w  w.  j ava  2s .  c o  m
    anchor.setRow1(ligne);
    anchor.setCol2(11);
    anchor.setRow2(ligne + 1);
    drawing.createPicture(anchor, pictureIdx);
    construitLigneExportCatalogueGeneric(wb, row, null, 10, mouvementStock);
}

From source file:org.bbreak.excella.reports.tag.ImageParamParser.java

License:Open Source License

/**
 * ??//  w w w  .  j a v  a 2s  .c o  m
 * 
 * @param sheet ?
 * @param cell 
 * @param filePath ?
 * @param dx1 ??
 * @param dy1 ???
 * @param scale ???
 * @throws ParseException
 */
public void replaceImageValue(Sheet sheet, Cell cell, String filePath, Integer dx1, Integer dy1, Double scale)
        throws ParseException {

    Workbook workbook = sheet.getWorkbook();

    int format = -1;
    if (filePath.toLowerCase().endsWith(JPEG_SUFFIX) || filePath.toLowerCase().endsWith(JPG_SUFFIX)) {
        format = Workbook.PICTURE_TYPE_JPEG;
    } else if (filePath.toLowerCase().endsWith(PNG_SUFFIX)) {
        format = Workbook.PICTURE_TYPE_PNG;
    }
    if (format == -1) {
        throw new ParseException(cell,
                "????????" + filePath);
    }

    byte[] bytes = null;
    InputStream is = null;
    try {
        is = new FileInputStream(filePath);
        bytes = IOUtils.toByteArray(is);
    } catch (Exception e) {
        throw new ParseException(cell, e);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            throw new ParseException(cell, e);
        }
    }

    int pictureIdx = workbook.addPicture(bytes, format);

    CreationHelper helper = workbook.getCreationHelper();

    @SuppressWarnings("rawtypes")
    Drawing drawing = drawingCash.get(sheet);
    if (drawing == null) {
        drawing = sheet.createDrawingPatriarch();
        drawingCash.put(sheet, drawing);
    }

    ClientAnchor anchor = helper.createClientAnchor();

    anchor.setRow1(cell.getRowIndex());
    anchor.setCol1(cell.getColumnIndex());
    anchor.setRow2(cell.getRowIndex() + 1);
    anchor.setCol2(cell.getColumnIndex() + 1);
    if (dx1 != null) {
        anchor.setDx1(dx1);
    }
    if (dy1 != null) {
        anchor.setDy1(dy1);
    }

    Picture picture = drawing.createPicture(anchor, pictureIdx);
    picture.resize(scale);

}

From source file:org.cgiar.ccafs.ap.summaries.projects.xlsx.BaseXLS.java

License:Open Source License

/**
 * @throws IOException/*  www  . ja v  a2 s. c  o m*/
 */
public void createLogo(Workbook workbook, Sheet sheet) throws IOException {
    // FileInputStream obtains input bytes from the image file
    InputStream inputStream =

            new FileInputStream(
                    new File(config.getResourcePath(), "templates" + File.separator + "logo-ccafs.png"));
    // Get the contents of an InputStream as a byte[].
    byte[] bytes = IOUtils.toByteArray(inputStream);
    // Adds a picture to the workbook
    int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
    // close the input stream
    inputStream.close();

    // Creates the top-level drawing patriarch.
    XSSFDrawing drawing = (XSSFDrawing) sheet.createDrawingPatriarch();

    // Set top-left corner for the image
    XSSFClientAnchor anchor = new XSSFClientAnchor();
    anchor.setAnchorType(2);
    anchor.setCol1(LOGO_POSITION_COLUMN);
    anchor.setRow1(LOGO_POSITION_ROW);

    // Creates a picture
    XSSFPicture pict = drawing.createPicture(anchor, pictureIdx);

    // Reset the image to the original size
    pict.resize();

}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.table.xls.helper.ExcelImageHandler.java

License:Open Source License

private int loadImage(final ImageContainer reference) throws IOException, UnsupportedEncoderException {
    final Workbook workbook = printerBase.getWorkbook();
    Image image = null;//ww  w  .ja v a  2  s  .  c  om
    // The image has an assigned URL ...
    if (reference instanceof URLImageContainer) {
        final URLImageContainer urlImage = (URLImageContainer) reference;
        final ResourceKey url = urlImage.getResourceKey();
        // if we have an source to load the image data from ..
        if (url != null && urlImage.isLoadable()) {
            // and the image is one of the supported image formats ...
            // we we can embedd it directly ...
            final int format = getImageFormat(url);
            if (format == -1) {
                // This is a unsupported image format.
                if (reference instanceof LocalImageContainer) {
                    final LocalImageContainer li = (LocalImageContainer) reference;
                    image = li.getImage();
                }
                if (image == null) {
                    try {
                        final Resource resource = resourceManager.create(url, null, Image.class);
                        image = (Image) resource.getResource();
                    } catch (final ResourceException re) {
                        logger.info("Failed to load image from URL " + url, re); // NON-NLS
                    }
                }
            } else {
                try {
                    final ResourceData data = resourceManager.load(url);
                    // create the image
                    return workbook.addPicture(data.getResource(resourceManager), format);
                } catch (final ResourceException re) {
                    logger.info("Failed to load image from URL " + url, re); // NON-NLS
                }

            }
        }
    }

    if (reference instanceof LocalImageContainer) {
        // Check, whether the imagereference contains an AWT image.
        // if so, then we can use that image instance for the recoding
        final LocalImageContainer li = (LocalImageContainer) reference;
        if (image == null) {
            image = li.getImage();
        }
    }

    if (image != null) {
        // now encode the image. We don't need to create digest data
        // for the image contents, as the image is perfectly identifyable
        // by its URL
        final byte[] data = RenderUtility.encodeImage(image);
        return workbook.addPicture(data, Workbook.PICTURE_TYPE_PNG);
    }
    return -1;
}

From source file:org.seasar.fisshplate.core.element.Picture.java

License:Apache License

/**
 * ??/*  w  ww .  j  a v a2 s  .c om*/
 *
 * @param picturepath
 * @param rowRangeIntVal
 * @param cellRangeIntVal
 * @param context
 * @throws FPMergeException
 */
private void writePicture(String picturepath, int cellRangeIntVal, int rowRangeIntVal, FPContext context)
        throws FPMergeException {

    FileInputStream imgFis = FileInputStreamUtil.createFileInputStream(picturepath);
    BufferedImage img = ImageIOUtil.read(imgFis);
    FileInputStreamUtil.close(imgFis);

    Workbook workbook = cell.getRow().getSheet().getWorkbook().getHSSFWorkbook();
    Drawing patriarch = context.getPartriarch();

    int imgWidth = img.getWidth();
    int imgHeight = img.getHeight();
    int cellNo = context.getCurrentCellNum();
    int rowNo = context.getCurrentRowNum();
    ClientAnchor anchor = createAnchor(imgWidth, imgHeight, cellNo, rowNo, cellRangeIntVal, rowRangeIntVal);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    String suffix = StringUtil.parseSuffix(picturepath);
    ImageIOUtil.write(img, suffix, baos);

    byte[] pictureData = baos.toByteArray();
    int pictureType = setupPictureType(suffix);
    int pictureIndex = workbook.addPicture(pictureData, pictureType);

    patriarch.createPicture(anchor, pictureIndex);

    ImageIOUtil.close(baos);
}

From source file:org.waterforpeople.mapping.dataexport.GraphicalSurveySummaryExporter.java

License:Open Source License

/**
 * Writes the report as an XLS document/*from   www  .  j  a  va  2s  .co m*/
 */
private void writeSummaryReport(Map<QuestionGroupDto, List<QuestionDto>> questionMap, SummaryModel summaryModel,
        String sector, Workbook wb) throws Exception {
    String title = sector == null ? SUMMARY_LABEL.get(locale) : sector;
    Sheet sheet = null;
    int sheetCount = 2;
    String curTitle = WorkbookUtil.createSafeSheetName(title);
    while (sheet == null) {
        sheet = wb.getSheet(curTitle);
        if (sheet == null) {
            sheet = wb.createSheet(WorkbookUtil.createSafeSheetName(curTitle));
        } else {
            sheet = null;
            curTitle = title + " " + sheetCount;
            sheetCount++;
        }
    }
    CreationHelper creationHelper = wb.getCreationHelper();
    Drawing patriarch = sheet.createDrawingPatriarch();
    int curRow = 0;
    Row row = getRow(curRow++, sheet);
    if (sector == null) {
        createCell(row, 0, REPORT_HEADER.get(locale), headerStyle);
    } else {
        createCell(row, 0, sector + " " + REPORT_HEADER.get(locale), headerStyle);
    }
    for (QuestionGroupDto group : orderedGroupList) {
        if (questionMap.get(group) != null) {
            for (QuestionDto question : questionMap.get(group)) {
                if (!(QuestionType.OPTION == question.getType() || QuestionType.NUMBER == question.getType())) {
                    continue;
                } else {
                    if (summaryModel.getResponseCountsForQuestion(question.getKeyId(), sector).size() == 0) {
                        // if there is no data, skip the question
                        continue;
                    }
                }
                // for both options and numeric, we want a pie chart and
                // data table for numeric, we also want descriptive
                // statistics
                int tableTopRow = curRow++;
                int tableBottomRow = curRow;
                row = getRow(tableTopRow, sheet);
                // span the question heading over the data table
                sheet.addMergedRegion(new CellRangeAddress(curRow - 1, curRow - 1, 0, 2));
                createCell(row, 0, getLocalizedText(question.getText(), question.getTranslationMap()),
                        headerStyle);
                DescriptiveStats stats = summaryModel.getDescriptiveStatsForQuestion(question.getKeyId(),
                        sector);
                if (stats != null && stats.getSampleCount() > 0) {
                    sheet.addMergedRegion(new CellRangeAddress(curRow - 1, curRow - 1, 4, 5));
                    createCell(row, 4, getLocalizedText(question.getText(), question.getTranslationMap()),
                            headerStyle);
                }
                row = getRow(curRow++, sheet);
                createCell(row, 1, FREQ_LABEL.get(locale), headerStyle);
                createCell(row, 2, PCT_LABEL.get(locale), headerStyle);

                // now create the data table for the option count
                Map<String, Long> counts = summaryModel.getResponseCountsForQuestion(question.getKeyId(),
                        sector);
                int sampleTotal = 0;
                List<String> labels = new ArrayList<String>();
                List<String> values = new ArrayList<String>();
                int firstOptRow = curRow;
                for (Entry<String, Long> count : counts.entrySet()) {
                    row = getRow(curRow++, sheet);
                    String labelText = count.getKey();
                    if (labelText == null) {
                        labelText = "";
                    }
                    StringBuilder builder = new StringBuilder();
                    if (QuestionType.OPTION == question.getType() && !DEFAULT_LOCALE.equals(locale)) {
                        String[] tokens = labelText.split("\\|");
                        // see if we have a translation for this option
                        for (int i = 0; i < tokens.length; i++) {
                            if (i > 0) {
                                builder.append("|");
                            }
                            if (question.getOptionContainerDto() != null
                                    && question.getOptionContainerDto().getOptionsList() != null) {
                                boolean found = false;
                                for (QuestionOptionDto opt : question.getOptionContainerDto()
                                        .getOptionsList()) {
                                    if (opt.getText() != null
                                            && opt.getText().trim().equalsIgnoreCase(tokens[i])) {
                                        builder.append(getLocalizedText(tokens[i], opt.getTranslationMap()));
                                        found = true;
                                        break;
                                    }
                                }
                                if (!found) {
                                    builder.append(tokens[i]);
                                }
                            }
                        }
                    } else {
                        builder.append(labelText);
                    }
                    createCell(row, 0, builder.toString(), null);
                    createCell(row, 1, count.getValue().toString(), null);

                    labels.add(builder.toString());
                    values.add(count.getValue().toString());
                    sampleTotal += count.getValue();
                }
                row = getRow(curRow++, sheet);
                createCell(row, 0, TOTAL_LABEL.get(locale), null);
                createCell(row, 1, sampleTotal + "", null);
                for (int i = 0; i < values.size(); i++) {
                    row = getRow(firstOptRow + i, sheet);
                    if (sampleTotal > 0) {
                        createCell(row, 2, PCT_FMT.format((Double.parseDouble(values.get(i)) / sampleTotal)),
                                null);
                    } else {
                        createCell(row, 2, PCT_FMT.format(0), null);
                    }
                }

                tableBottomRow = curRow;

                if (stats != null && stats.getSampleCount() > 0) {
                    int tempRow = tableTopRow + 1;
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, "N", null);
                    createCell(row, 5, sampleTotal + "", null);
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, MEAN_LABEL.get(locale), null);
                    createCell(row, 5, stats.getMean() + "", null);
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, STD_E_LABEL.get(locale), null);
                    createCell(row, 5, stats.getStandardError() + "", null);
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, MEDIAN_LABEL.get(locale), null);
                    createCell(row, 5, stats.getMedian() + "", null);
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, MODE_LABEL.get(locale), null);
                    createCell(row, 5, stats.getMode() + "", null);
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, STD_D_LABEL.get(locale), null);
                    createCell(row, 5, stats.getStandardDeviation() + "", null);
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, VAR_LABEL.get(locale), null);
                    createCell(row, 5, stats.getVariance() + "", null);
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, RANGE_LABEL.get(locale), null);
                    createCell(row, 5, stats.getRange() + "", null);
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, MIN_LABEL.get(locale), null);
                    createCell(row, 5, stats.getMin() + "", null);
                    row = getRow(tempRow++, sheet);
                    createCell(row, 4, MAX_LABEL.get(locale), null);
                    createCell(row, 5, stats.getMax() + "", null);
                    if (tableBottomRow < tempRow) {
                        tableBottomRow = tempRow;
                    }
                }
                curRow = tableBottomRow;
                if (labels.size() > 0) {
                    boolean hasVals = false;
                    if (values != null) {
                        for (String val : values) {
                            try {
                                if (val != null && new Double(val.trim()) > 0D) {
                                    hasVals = true;
                                    break;
                                }
                            } catch (Exception e) {
                                // no-op
                            }
                        }
                    }
                    // only insert the image if we have at least 1 non-zero
                    // value
                    if (hasVals && generateCharts) {
                        // now insert the graph
                        int indx = wb.addPicture(JFreechartChartUtil.getPieChart(labels, values,
                                getLocalizedText(question.getText(), question.getTranslationMap()), CHART_WIDTH,
                                CHART_HEIGHT), Workbook.PICTURE_TYPE_PNG);
                        ClientAnchor anchor = creationHelper.createClientAnchor();
                        anchor.setDx1(0);
                        anchor.setDy1(0);
                        anchor.setDx2(0);
                        anchor.setDy2(255);
                        anchor.setCol1(6);
                        anchor.setRow1(tableTopRow);
                        anchor.setCol2(6 + CHART_CELL_WIDTH);
                        anchor.setRow2(tableTopRow + CHART_CELL_HEIGHT);
                        anchor.setAnchorType(2);
                        patriarch.createPicture(anchor, indx);
                        if (tableTopRow + CHART_CELL_HEIGHT > tableBottomRow) {
                            curRow = tableTopRow + CHART_CELL_HEIGHT;
                        }
                    }
                }

                // add a blank row between questions
                getRow(curRow++, sheet);
                // flush the sheet so far to disk; we will not go back up
                ((SXSSFSheet) sheet).flushRows(0); // retain 0 last rows and
                // flush all others

            }
        }
    }
}

From source file:packtest.WorkingWithPictures.java

License:Apache License

public static void main(String[] args) throws IOException {

    //create a new workbook
    Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
    try {// w w  w.j a v  a  2 s.c  o m
        CreationHelper helper = wb.getCreationHelper();

        //add a picture in this workbook.
        InputStream is = new FileInputStream(args[0]);
        byte[] bytes = IOUtils.toByteArray(is);
        is.close();
        int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);

        //create sheet
        Sheet sheet = wb.createSheet();

        //create drawing
        Drawing drawing = sheet.createDrawingPatriarch();

        //add a picture shape
        ClientAnchor anchor = helper.createClientAnchor();
        anchor.setCol1(1);
        anchor.setRow1(1);
        Picture pict = drawing.createPicture(anchor, pictureIdx);

        //auto-size picture
        pict.resize(2);

        //save workbook
        String file = "picture.xls";
        if (wb instanceof XSSFWorkbook)
            file += "x"; // NOSONAR
        OutputStream fileOut = new FileOutputStream(file);
        try {
            wb.write(fileOut);
        } finally {
            fileOut.close();
        }
    } finally {
        wb.close();
    }
}

From source file:poi.xssf.usermodel.examples.WorkingWithPictures.java

License:Apache License

public static void main(String[] args) throws IOException {

    //create a new workbook
    Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
    CreationHelper helper = wb.getCreationHelper();

    //add a picture in this workbook.
    InputStream is = new FileInputStream(args[0]);
    byte[] bytes = IOUtils.toByteArray(is);
    is.close();//w w w  .ja  v  a 2s .  c o  m
    int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);

    //create sheet
    Sheet sheet = wb.createSheet();

    //create drawing
    Drawing drawing = sheet.createDrawingPatriarch();

    //add a picture shape
    ClientAnchor anchor = helper.createClientAnchor();
    anchor.setCol1(1);
    anchor.setRow1(1);
    Picture pict = drawing.createPicture(anchor, pictureIdx);

    //auto-size picture
    pict.resize(2);

    //save workbook
    String file = "picture.xls";
    if (wb instanceof XSSFWorkbook)
        file += "x";
    FileOutputStream fileOut = new FileOutputStream(file);
    wb.write(fileOut);
    fileOut.close();
}