赞
踩
话不多说,直接上代码,具体的实现方法如下:
// 方法中用到的宏定义 private static final short TWIPS_PER_PIEXL = 15; // 1 Pixel = 1440 TPI / 96 DPI = 15 Twips private static final double THGPS_PER_PIEXL = 2.5; public static XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream("D\\test\\test.xlsx"));; /* * 插入图片 * file 图片路线径 * c1 excel中的开始列 * r1 excel中的开始行 * c2 excel中的结束列 * r2 excel中的结束行 * cellWidth 图片宽度 * cellHeight 图片高度 * */ public void insertImage(File file, int c1, int r1, int c2, int r2, int cellWidth, int cellHeight) { try { ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); Image src; System.out.println("==> 图片路径 " + file.getPath()); if (file.getPath().endsWith(".bmp") || file.getPath().endsWith(".BMP")) { BufferedImage bi = ImageIO.read(file); ImageProducer producer = bi.getSource(); Toolkit toolkit = Toolkit.getDefaultToolkit(); src = toolkit.createImage(producer); } else { src = Toolkit.getDefaultToolkit().getImage(file.getPath()); } BufferedImage bufferImg = toBufferedImage(src); int imageWidthPixel = bufferImg.getWidth(); int imageHeightPixel = bufferImg.getHeight(); double imageWidth = pixel2PoiWidth(imageWidthPixel); double imageHeight = pixel2PoiHeight(imageHeightPixel); ImageIO.write(bufferImg, "jpg", byteArrayOut); System.out.println(); // 根据需求对图片进行微调 XSSFClientAnchor anchor = new XSSFClientAnchor(XSSFShape.EMU_PER_POINT * 5, XSSFShape.EMU_PER_POINT * 5, XSSFShape.EMU_PER_POINT * -5, XSSFShape.EMU_PER_POINT * -5, c1, r1, c2, r2); anchor.setAnchorType(3); XSSFPicture pic = patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG)); byteArrayOut.flush(); byteArrayOut.close(); } catch (IOException e) { e.printStackTrace(); } } private static int getColsWidth(XSSFSheet sheet, int firstCol, int colCnt) { int colWidth = 0; for (int i = firstCol; i < firstCol + colCnt; i++) { colWidth = colWidth + sheet.getColumnWidth(i); } return colWidth; } private static int getRowsHeight(XSSFSheet sheet, int firstRow, int rowCnt) { int rowHeight = 0; for (int i = firstRow; i < firstRow + rowCnt; i++) { rowHeight += sheet.getRow(i).getHeight(); } return rowHeight; } public static double poiHeight2Pixel(double height) { return height / TWIPS_PER_PIEXL; } // 像素转poi宽度 public static double pixel2PoiWidth(double pixel) { double numChars = pixel * TWIPS_PER_PIEXL * THGPS_PER_PIEXL; return numChars; }
调用方法
// 首先确定好图片范围,即excel中的开始行/列和结束行/列
int beginCol = CellReference.convertColStringToIndex("B");
int endCol = CellReference.convertColStringToIndex("L");
int beginRow = 3;
int endRow = 23;
// 获取图片的高和宽,即图片范围内单元格的总高和总宽
int picHeight = getRowsHeight(sheet, beginRow , endRow );
int picWidth = getColsWidth(sheet, beginCol , endCol );
// 进行图片插入处理
File picFile = new File("D:\\test\\testpic.jpg");
insertImage(picFile, beginCol , beginRow , endCol ,endRow , picWidth , picHeight );
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。