直接上代码
FileOutputStream fileOut = null;
BufferedImage bufferImg = null;
BufferedImage bufferImgU = null;
BufferedImage bufferImgP = null;
BufferedImage bufferImgI= null;
try {
// 先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray
// 读入图片1
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
bufferImg = ImageIO.read(new File(imgPath+"/chart.png"));
ImageIO.write(bufferImg, "png", byteArrayOut);
// 读入图片2
ByteArrayOutputStream byteArrayOutU = new ByteArrayOutputStream();
bufferImgU = ImageIO.read(new File(imgPath+"/url.png"));
ImageIO.write(bufferImgU, "png", byteArrayOutU);
// 读入图片3
ByteArrayOutputStream byteArrayOutI= new ByteArrayOutputStream();
bufferImgI = ImageIO.read(new File(imgPath+"/inter.png"));
ImageIO.write(bufferImgI, "png", byteArrayOutI);
// 读入图片4
ByteArrayOutputStream byteArrayOutP = new ByteArrayOutputStream();
bufferImgP = ImageIO.read(new File(imgPath+"/part.png"));
ImageIO.write(bufferImgP, "png", byteArrayOutP);
// 创建一个工作薄
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet1 = wb.createSheet("test picture");
HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 255, 255,
(short) 1, 1, (short) 5, 5);
anchor.setAnchorType(3);
HSSFClientAnchor anchoru = new HSSFClientAnchor(0, 0, 255, 255,
(short) 1, 6, (short) 5, 10);
anchoru.setAnchorType(3);
HSSFClientAnchor anchorI = new HSSFClientAnchor(0, 0, 255, 255,
(short) 6, 1, (short) 10, 5);
anchorI.setAnchorType(3);
HSSFClientAnchor anchorP = new HSSFClientAnchor(0, 0, 255, 255,
(short) 6, 6, (short) 10, 10);
anchorP.setAnchorType(3);
// 插入图片1
patriarch.createPicture(anchor, wb.addPicture(byteArrayOut
.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
// 插入图片2
patriarch.createPicture(anchoru, wb.addPicture(byteArrayOutU
.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
// 插入图片1
patriarch.createPicture(anchorI, wb.addPicture(byteArrayOutI
.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
// 插入图片2
patriarch.createPicture(anchorP, wb.addPicture(byteArrayOutP
.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
fileOut = new FileOutputStream(path+"/每日报表.xls");
// 写入excel文件
wb.write(fileOut);
fileOut.close();
} catch (IOException io) {
io.printStackTrace();
System.out.println("erorr : " + io.getMessage());
} finally {
if (fileOut != null) {
try {
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
一篇很好的介绍文章:http://blog.csdn.net/chenssy/article/details/20524563