poi 实现插入图片

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();
		}
	}
}

效果

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值