当前位置: 代码迷 >> Web前端 >> 在Excel中安插图片
  详细解决方案

在Excel中安插图片

热度:396   发布时间:2012-09-28 00:03:35.0
在Excel中插入图片

例子实现了在Excel中插入图片.

/**
?*? java实现在excel中插入图片
?*/
package com.together.nms.dt.data.model.hibernate.test;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JOptionPane;

import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class testPoiPicture {

?/**
? * @param args
? */
?public static void main(String[] args) {
??FileOutputStream fileOut = null;
??BufferedImage bufferImg = null;
??BufferedImage bufferImg1 = null;
??try {
???// 先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray
???// 读入图片1
???ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
???bufferImg = ImageIO.read(new File("c:\\1285748103156_000.jpg"));
???ImageIO.write(bufferImg, "jpg", byteArrayOut);

???// 读入图片2
???// ByteArrayOutputStream byteArrayOut1 = new
???// ByteArrayOutputStream();
???// bufferImg1 = ImageIO.read(new File("F:\\photo\\baby\\104.png"));
???// ImageIO.write(bufferImg1, "png", byteArrayOut1);

???// 创建一个工作薄
???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 anchor1 = new HSSFClientAnchor(0, 0, 255, 255,
?????(short) 6, 6, (short) 10, 10);
???// anchor1.setAnchorType(3);
???// 插入图片1
???patriarch
?????.createPicture(anchor, wb.addPicture(
???????byteArrayOut.toByteArray(),
???????HSSFWorkbook.PICTURE_TYPE_JPEG));
???// 插入图片2
???// patriarch.createPicture(
???// anchor1,
???// wb.addPicture(byteArrayOut1.toByteArray(),
???// HSSFWorkbook.PICTURE_TYPE_PNG)).resize(0.5);

???fileOut = new FileOutputStream("d:/testbook.xls");
???// 写入excel文件
???wb.write(fileOut);
???JOptionPane.showMessageDialog(null, "图片已经成功导入到 : " + fileOut);
???fileOut.close();
??} catch (IOException io) {
???JOptionPane.showMessageDialog(null, "图片导入失败,错误信息 :" + io
?????+ "\n错误原因可能是图片已经打开。");
???io.printStackTrace();
???System.out.println("erorr : " + io.getMessage());
??} finally {
???if (fileOut != null) {
????try {
?????fileOut.close();
????} catch (IOException e) {
?????e.printStackTrace();
????}
???}
??}
?}
}

上面代码,已经经过测试,呵呵!!

  相关解决方案