Excel poi 图片写入

代码

/**
     * 
     * @param wb  工作簿
     * @param patriarch 绘图
     * @param imageUrl 图片地址
     * @param row 行对象
     * @param column 图片存储列的序号
     */
    private void drawPictureInfoExcel(Workbook wb, XSSFDrawing patriarch, String imageUrl, Row row, int column)  {
        //rowIndex代表当前行
        if (!StringUtils.isEmpty(imageUrl) && !"null".equals(imageUrl)) {
            int rowIndex = row.getRowNum();
            ByteArrayOutputStream os = null;
            try {
				/**
					本地图片
					File file = new File(imagePath);
					BufferedImage image= ImageIO.read(file);
				*/
                URL url = new URL(imageUrl);
                BufferedImage image = ImageIO.read(url);
                os = new ByteArrayOutputStream();
                ImageIO.write(image, "png", os);
                int width = image.getWidth();
                int height = image.getHeight();
                //宽度固定,高度按比例计算
                int a = 20000, b = 30000, c = 1270000, d = 1270000 * height / width; 
                int minHeight = (int) Math.floor(d / 650) + 100;
                if (row.getHeight() < minHeight) {
                    row.setHeight((short) (minHeight));
                    XSSFClientAnchor anchor = new XSSFClientAnchor(a, b, c, d, (short) column, rowIndex, (short) column, rowIndex);
                    anchor.setAnchorType(ClientAnchor.AnchorType.byId(0));
                    patriarch.createPicture(anchor, wb.addPicture(os.toByteArray(), XSSFWorkbook.PICTURE_TYPE_PNG));
                }
            } catch (final Exception e) {
                e.printStackTrace();
            }finally {
                if(os!=null){
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

	/**
     * 获取绘图
     */
    public Drawing<?> getDrawingPatriarch () {
	    if (sheet.getDrawingPatriarch() == null) {
	        sheet.createDrawingPatriarch();
	    }
    	return sheet.getDrawingPatriarch();
    }
调用
 drawPictureInfoExcel(wb,(XSSFDrawing)getDrawingPatriarch(),img_path,row,column);
其他
//ImageIo获取二进制数据方法
BufferedImage image = ImageIO.read(url);
byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();

你可能感兴趣的:(excel,java)