?!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
在POI中有HSSFPatriarch对象Q该对象为画囄理器,它的createPicture(anchor, pictureIndex)Ҏp够在Excel插入一张图片。所以要在Excel中插入图片,三步可以搞定。一、获取HSSFPatriarch对象Q二、new HSSFClientAnchor对象Q三、调用createPictureҎ卛_。实现倒是非常Ҏ实现Q如果想把它做好q是有点儉K度的。这里我们先插入一张图片:
复制代码
public class ExcelImageTest {
public static void main(String[] args) {
FileOutputStream fileOut = null;
BufferedImage bufferImg = null;
//先把读进来的囄攑ֈ一个ByteArrayOutputStream中,以便产生ByteArray
try {
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
bufferImg = ImageIO.read(new File("F:/囄/照片/无名?昭11.jpg"));
ImageIO.write(bufferImg, "jpg", byteArrayOut);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet1 = wb.createSheet("test picture");
//d的顶U管理器Q一个sheet只能获取一个(一定要注意q点Q?/span>
HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();
//anchor主要用于讄囄的属?/span>
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 255, 255,(short) 1, 1, (short) 5, 8);
anchor.setAnchorType(3);
//插入囄
patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
fileOut = new FileOutputStream("D:/试Excel.xls");
// 写入excel文g
wb.write(fileOut);
System.out.println("----Excle文g已生?-----");
} catch (Exception e) {
e.printStackTrace();
}finally{
if(fileOut != null){
try {
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
复制代码
如下为执行后的结果:
POI_01
至于Z么会是这Ll果Q主要是因ؓHSSFClientAnchor(0, 0, 255, 255,(short) 1, 1, (short) 5, 8)q个构造函数造成的,下面我就来解释这个构造函敎ͼHSSFClientAnchor(int dx1,int dy1,int dx2,int dy2,short col1,int row1,short col2, int row2);各个参数的含义如下:
dx1Qthe x coordinate within the first cell?/span>
dy1Qthe y coordinate within the first cell?/span>
dx2Qthe x coordinate within the second cell?/span>
dy2Qthe y coordinate within the second cell?/span>
col1Qthe column (0 based) of the first cell?/span>
row1Qthe row (0 based) of the first cell?/span>
col2Qthe column (0 based) of the second cell?/span>
row2Qthe row (0 based) of the second cell?/span>
q里dx1、dy1定义了该囄在开始cell的v始位|,dx2、dy2定义了在lcell的结束位|。col1、row1定义了开始cell、col2、row2定义了结束cell?/span>
POI_02
下面是有两个不同的构造函数所创徏的,从这q图中我们可以清晰看C面八个参数的含义和不同之处?/span>
POI_03
上面是插入一张图片,那么实现插入多张囄呢?其实很简单,构造多个不同的HSSFClientAnchor对象Q控制好那八个参敎ͼ如下Q?/span>
HSSFClientAnchor anchor1 = new HSSFClientAnchor(0, 0, 1023,100,(short) 1, 1, (short)5, 8);
HSSFClientAnchor anchor2 = new HSSFClientAnchor(0, 0, 1023,100,(short) 1, 9, (short)5, 16);
//插入囄
patriarch.createPicture(anchor1, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
patriarch.createPicture(anchor2, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));