直接上代码:
public static void main(String[] args) throws Exception {
FileOutputStream fileOut = null;
/*
*
* 目的:操作图片 实现:第一步-需要将图片从磁盘加载到内存中,第二步-java中有Image和BufferedImage这两种处理图片的类,
*
* 第一种类似copy,不能对 图片进行操作,而BufferedImage则是将图片放入内存图片缓冲区中,可以对图片进行修改。
*
*/
BufferedImage bufferImg = null;
// 先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray
try {
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
bufferImg = ImageIO.read(new File("d:/aa/123.jpg"));
ImageIO.write(bufferImg, "png", byteArrayOut);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet1 = wb.createSheet("test picture");
// 画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)
HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();
/**
* 该构造函数有8个参数
* 前四个参数是控制图片在单元格的位置,分别是图片距离单元格left,top,right,bottom的像素距离
* 后四个参数,前连个表示图片左上角所在的cellNum和 rowNum,后天个参数对应的表示图片右下角所在的cellNum和 rowNum,
* excel中的cellNum和rowNum的index都是从0开始的
*
*/
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 255, 255, (short) 1, 1, (short) 5, 8);
// 插入图片
patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
File file = new File("d:/aa/123.xls");
file.createNewFile();
fileOut = new FileOutputStream(file);
// 写入excel文件
wb.write(fileOut);
System.out.println("----Excel文件已生成------");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileOut != null) {
try {
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
希望对你有所帮助!