public class PoiInsertPic2 {
public static void insertPicCost(Workbook workBook,Sheet topPic,String pic){
BufferedImage bufferImg = null;//图片
try {
// 先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
//将图片读到BufferedImage
bufferImg = ImageIO.read(new File(pic));
// 将图片写入流中
ImageIO.write(bufferImg, "png", byteArrayOut);
// 利用HSSFPatriarch将图片写入EXCEL
XSSFDrawing patriarch = (XSSFDrawing) topPic.createDrawingPatriarch();
//图片一导出到单元格B2中
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0,
(short) 0, 0, (short) 10, 30);
// 插入图片
patriarch.createPicture(anchor, workBook.addPicture(byteArrayOut
.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
System.out.println("插入成功" );
} catch (IOException io) {
io.printStackTrace();
System.out.println("插入失败 : " + io.getMessage());
} finally {
}
}
public static void main(String[] args) {
try {
String pic1 = "E:/aa.png";
Workbook workBook = new SXSSFWorkbook(100);
Sheet topPic = workBook.createSheet("top20图");
String savePath = "E:/aaa.xlsx";
File file = new File(savePath);
if (!file.exists()) {
file.createNewFile();
}
insertPicCost(workBook,topPic,pic1);
FileOutputStream os = new FileOutputStream(savePath);
workBook.write(os);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
效果