import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelPicTest {
public static void main(String[] args) {
try {
// 创建一个excel文件
XSSFWorkbook workbook = new XSSFWorkbook();
// 获取第一个表格
Sheet sheet0 = workbook.createSheet();
// 画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)
XSSFDrawing patriarch = (XSSFDrawing) sheet0.createDrawingPatriarch();
// 图片定位
// 参数说明
// int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2,
// int row2
// dx1,dy1,dx2,dy2一般用不到,标识单元格内的x,y
// **********************以下四个参数定位图片的具体存放位置*********************
// col1:the column (0 based) of the first cell.
// row1:the row (0 based) of the first cell.
// col2: the column (0 based) of the second cell.
// row2: the row (0 based) of the second cell.
// **********************以上四个参数用来定位两个单元格,都是从索引0开始的************
// col1/row1定位图片开始的左上角位置(包含当前单元格),这里传递的1,1表示图片左上角为第2行(索引从0开始1表示第二行)第二个单元格(索引从0开始1表示第二行)开始
// col2/row2定位图片的右下角位置(不含),这里的8,5标识结束为6行(索引从0开始1表示第二行)第9格单元格(索引从0开始1表示第二行)结束
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 1, 1, 8, 5);
//
FileInputStream fis = new FileInputStream(new File("d:/1.jpg"));
byte[] image = input2byte(fis);// 图片
patriarch.createPicture(anchor, workbook.addPicture(image, HSSFWorkbook.PICTURE_TYPE_PNG));// 写图片
// excel文件输出
File excel = new File("d://t1.xlsx");
workbook.write(new FileOutputStream(excel));
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static final byte[] input2byte(InputStream inStream) throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] in2b = swapStream.toByteArray();
return in2b;
}
}
执行结果:
http://blog.xqlee.com/article/110.html