java类中加入图片_Java POI在excel文件里插入图片

1.添加POI的maven依赖

org.apache.poi

poi

3.15

org.apache.poi

poi-ooxml

3.15

2.案例代码

XSSFClientAnchor类的8个重要参数:

/**

* Creates a new client anchor and sets the top-left and bottom-right

* coordinates of the anchor.

*

* @param dx1 设置为0即可

* @param dy1 设置为0即可

* @param dx2 设置为0即可

* @param dy2 设置为0即可

* @param col1 图片所在位置的起始列(以第0列为基准,包含)

* @param row1 图片所在位置的起始行(以第0行为基准,包含)

* @param col2 图片所在位置的中止列(以第0列为基准,不包含)

* @param row2 图片所在位置的中止行(以第0行为基准,不包含)

*/

public XSSFClientAnchor(int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2) {

this();

cell1.setCol(col1);

cell1.setColOff(dx1);

cell1.setRow(row1);

cell1.setRowOff(dy1);

cell2.setCol(col2);

cell2.setColOff(dx2);

cell2.setRow(row2);

cell2.setRowOff(dy2);

}

核心代码

import org.apache.commons.io.FileUtils;

import org.apache.poi.ss.usermodel.ClientAnchor;

import org.apache.poi.xssf.usermodel.*;

import javax.imageio.ImageIO;

import java.awt.image.BufferedImage;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.net.URL;

public class TestOperationExcel {

private static String fileName = "F://demo.xlsx";

public static void main(String[] args) throws Exception{

createExcelWithImage();

}

public static void createExcelWithImage() throws Exception {

//创建一个excel文件,名称为:

XSSFWorkbook workbook = new XSSFWorkbook();

//创建一个sheet,名称为工作簿1

XSSFSheet sheet = workbook.createSheet("工作簿1");

BufferedImage bufferImg = null;

//先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray

ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();

String imageUrl = "https://img2018.cnblogs.com/i-beta/1278703/201911/1278703-20191128121650595-812419505.png";

//获取图片后缀

String imageType = imageUrl.substring(imageUrl.length()-3);

File imageFile = new File("./temp." + imageType);

FileUtils.copyURLToFile(new URL(imageUrl), imageFile);

bufferImg = ImageIO.read(imageFile);

ImageIO.write(bufferImg, imageType, byteArrayOut);

//画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)

XSSFDrawing patriarch = sheet.createDrawingPatriarch();

//anchor主要用于设置图片的属性

XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) 2, 2, (short) 4, 4);

anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);

//插入图片

patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));

FileOutputStream fileOutputStream = new FileOutputStream(fileName);

workbook.write(fileOutputStream);

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值