public static void cacheWritePicture(BufferedImage bufferImg, Sheet sheet, Workbook wb, int width, int height, int col1, int row1, int col2, int row2) throws Exception {
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
ImageIO.write(bufferImg, "jpg", byteArrayOut);
SXSSFDrawing drawing = (SXSSFDrawing) sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor( XSSFShape.EMU_PER_PIXEL * 17, XSSFShape.EMU_PER_PIXEL * 17, width, height, col1, row1, col2, row2); //画图的顶级管理器,一个sheet只能获取一个(一定要注意这点) //AnchorType.MOVE_AND_RESIZE,此时才可以设置图片的绝对宽度和高度,要不然,图片的宽度和高度,可能设置没有效果 anchor.setAnchorType(AnchorType.MOVE_AND_RESIZE); //插入图片 drawing.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG)); }
anchor.setAnchorType(AnchorType.MOVE_AND_RESIZE);//注意:这行代码是关键
width和height都是:
XSSFShape.EMU_PER_PIXEL * 100
注意:如果,图片要放在一个单元格里面,col1和col2要相同,row1和row2也要相同.