使用JXL将图像插入到excel文件中,而不用拉伸

我可以插入图像到我的Excel文件使用jxl使用sheet.addImage(WritableImage obj) 。 我的问题是,它基于WritableImage的参数拉伸。 我想知道是否有一种方式,以便我插入的图像不会拉伸,如果我插入一个200×200大小的图像,它会出现在表中200×200。

就像这个问题一直困扰着我,关于jxl,我从来没有find一种方法来插入一个图像,而不是像素/英寸/任何标准的测量单位的宽高比与细胞的关联,我已经做了体面的研究这样做。

最好的办法是将图像调整为插入的单元格的高度/宽度,或者更好的方法是为要放置图像的单元格设置单元格宽度/高度。

从JExcel常见问题 – http://jexcelapi.sourceforge.net/resources/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 = ImageIO.read(imageFile); 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())); 

要保持纵横比,如果用户更改行高或列宽,则还需要将WritableImage设置为不重新resize。 使用下面的任何一种方法(如果您希望locking图像锚定点或根据resize移动您的偏好):

 WritableImage.MOVE_WITH_CELLS; WritableImage.NO_MOVE_OR_SIZE_WITH_CELLS; 

其实这是可能的。 假设你想要包含的图片的宽度是4000.然后你执行以下操作:

 CellView cv = excelSheetTemp.getColumnView(0); //get the width of the column where you want to insert the picture int width = forLogo.getSize(); //if the width is less than the size you want, set the column width to //the width. This will ensure that your image does not shrink if (width < 4000) { forLogo.setSize(4000); excelSheetTemp.setColumnView(0, cv); width = 4000; } double c = 4000/width; WritableImage im = new WritableImage(0, 1, c, 3, the image file); excelSheetTemp.addImage(im);