JavaRanch Home    
 
This page:         last edited 05 January 2010         What's Changed?         Edit

Create Excel With Image   

This code example shows how to use the Apache POI library to create an Excel file that contains an image (either a local file, or downloaded from the net).


import java.io.*;
import java.net.URL;

import org.apache.poi.hssf.usermodel.*;

public class CreateExcelWithImage {

    public static void main (String[] args) throws IOException {
        // the image will go into cell (1,1)
        int colIdx = 1, rowIdx = 1;

        URL url = new URL("http://poi.apache.org/resources/images/project-logo.jpg");
        InputStream is = url.openStream();
        // load an image from disk instead of from the net
        // InputStream is = new FileInputStream("project-logo.jpg");

        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("image");
        for (int i=0; i<=rowIdx; i++)
            sheet.createRow(i);

        // enlarge image cell
        sheet.setColumnWidth(colIdx, 5000);
        sheet.getRow(rowIdx).setHeightInPoints(100);

        // read image into memory
        ByteArrayOutputStream img_bytes = new ByteArrayOutputStream();
        int b;
        while ((b = is.read()) != -1)
            img_bytes.write(b);
        is.close();
        HSSFClientAnchor anchor = new HSSFClientAnchor(0000, (short) colIdx, rowIdx,
                                                                  (short) (colIdx+1), rowIdx+1);
            // other possible image types are: PICTURE_TYPE_PICT, PICTURE_TYPE_PNG,
            //                                 PICTURE_TYPE_WMF, PICTURE_TYPE_DIB, PICTURE_TYPE_EMF
        int index = wb.addPicture(img_bytes.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG);
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        patriarch.createPicture(anchor, index);
            // anchor type: ClientAnchor.MOVE_AND_RESIZE
            //              ClientAnchor.MOVE_DONT_RESIZE
            //              ClientAnchor.DONT_MOVE_AND_RESIZE
        anchor.setAnchorType(ClientAnchor.MOVE_DONT_RESIZE);

        // write file to disk
        FileOutputStream fos = new FileOutputStream("image.xls");
        wb.write(fos);
        fos.close();
    }
}


CategoryCodeSamples CodeBarn

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton