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

}

 

你可能感兴趣的:(POI)