1 package com.sun.office.excel;
2 3 import java.awt.image.BufferedImage; 4 import java.io.ByteArrayOutputStream; 5 import java.io.File; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 9 import javax.imageio.ImageIO;10 11 import org.apache.poi.hssf.usermodel.HSSFClientAnchor;12 import org.apache.poi.hssf.usermodel.HSSFPatriarch;13 import org.apache.poi.hssf.usermodel.HSSFSheet;14 import org.apache.poi.hssf.usermodel.HSSFWorkbook;15 16 public class ExcelImageDemo { 17 18 public static void main(String[] args) { 19 FileOutputStream fileOut = null;20 BufferedImage bufferImg = null;21 // 先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray22 try { 23 ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();24 bufferImg = ImageIO.read(new File("D:/ubuntn.jpg"));25 ImageIO.write(bufferImg, "jpg", byteArrayOut);26 27 HSSFWorkbook wb = new HSSFWorkbook();28 HSSFSheet sheet1 = wb.createSheet("test picture");29 // 画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)30 HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();31 for (int i = 0; i < 3; i++) { 32 // anchor主要用于设置图片的属性33 HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 250, (short) 1, 1+i*10, (short) 5, 8+i*10);34 // 插入图片35 patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));36 }37 HSSFSheet sheet2 = wb.createSheet("test picture2");38 //第二个sheet页39 HSSFPatriarch patriarch2 = sheet2.createDrawingPatriarch();40 for (int i = 0; i < 3; i++) { 41 // anchor主要用于设置图片的属性42 HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 250, (short) 1, 1+i*10, (short) 5, 8+i*10);43 // 插入图片44 patriarch2.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));45 }46 fileOut = new FileOutputStream("Excel.xls");47 // 写入excel文件48 wb.write(fileOut);49 System.out.println("----Excle文件已生成------");50 } catch (Exception e) { 51 e.printStackTrace();52 } finally { 53 if (fileOut != null) { 54 try { 55 fileOut.close();56 } catch (IOException e) { 57 e.printStackTrace();58 }59 }60 }61 }62 // 关于HSSFClientAnchor(dx1,dy1,dx2,dy2,col1,row1,col2,row2)的参数,有必要在这里说明一下:63 // dx1:起始单元格的x偏移量,64 // dy1:起始单元格的y偏移量,65 // dx2:终止单元格的x偏移量,66 // dy2:终止单元格的y偏移量,67 // col1:起始单元格列序号,从0开始计算;68 // row1:起始单元格行序号,从0开始计算,69 // col2:终止单元格列序号,从0开始计算;70 // row2:终止单元格行序号,从0开始计算,71 //添加多个图片时:多个pic应该share同一个DrawingPatriarch在同一个sheet里面。72 }