java向excel中插入图片
生活随笔
收集整理的這篇文章主要介紹了
java向excel中插入图片
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
話不多說,直接上代碼,具體的實現方法如下:
// 方法中用到的宏定義 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 );總結
以上是生活随笔為你收集整理的java向excel中插入图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 弄清std::chrono::syste
- 下一篇: RJ45和RJ11接插件定义和有关规定