Jemp Jemp - 1 year ago 156
Java Question

Insert image to excel file using JXL without stretching it

I can insert image to my excel file using jxl using

sheet.addImage(WritableImage obj)
. My problem is that, it stretches based on the args of
. I'm wondering if there is a way so that the image that I insert will not stretch like if I insert a 200x200 sized image it will appear to the sheet as 200x200.

Answer Source

As much as this has bugged me about jxl, I've never found a way to insert an image without associating the aspect ratio to cells instead of pixels/inches/any standard unit of measurement, and I've done decent research in the past on doing so.

The best you can do is to adapt the images to the height/width of the cells you are inserting it into, or even better, set the cell width/height for the cells you are putting the image in.

From the JExcel FAQ-

private static final double CELL_DEFAULT_HEIGHT = 17;
private static final double CELL_DEFAULT_WIDTH = 64;

File imageFile = new File(GIF_OR_JPG_IMAGE_FILE);
BufferedImage input =;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(input, "PNG", baos);
sheet.addImage(new WritableImage(1,1,input.getWidth() / CELL_DEFAULT_WIDTH,
    input.getHeight() / CELL_DEFAULT_HEIGHT,baos.toByteArray()));

To keep the aspect ratio, you'll also want to set the WritableImage to not re-size if the user changes the row height or column width. Do this with either of the below (your preference based on if you want the image anchor locked or to move with resizing):