java POI 插入图片到Excel文件

 1.添加POI依赖

		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.17</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.17</version>
		</dependency>

2.使用XSSFDrawing 插入图片到excel文件

参考java POI实现向Excel中插入图片    java 在Excel中插入图片 POI实现

XSSFDrawing patri = (XSSFDrawing) sheet.createDrawingPatriarch();
// col1,row1 开始单元格 列和行,从0下标开始
// col2,row2 开始单元格 列和行,从1下标开始
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 255, 255, col1, row1, col2, row2);
patri.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_PNG));

 

import java.awt.image.BufferedImage;
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 java.io.OutputStream;

import javax.imageio.ImageIO;

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 PoiExcelInsertPic {

	private static String excelFilePath = "C:/TEST/test.xlsx";
	private static String imagePath = "C:/TEST/image.PNG";

	// picture 原始位置 第13行 4,5两列
	private static short picCol1 = 3;
	private static short picCol2 = 5; // D and E
	private static int picRow1 = 12;
	private static int picRow2 = 13; // 第13行

	public static void main(String[] args) {

		try {
			insertPic(excelFilePath, imagePath, picCol1, picRow1, picCol2, picRow2);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 5.往Excel文件插入图片
	public static void insertPic(String filePath, String imagePath, short col1, int row1, short col2, int row2)
			throws IOException {
		FileOutputStream fileOut = null;
		BufferedImage bufferImg = null;

		// 先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray
		ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
		bufferImg = ImageIO.read(new File(imagePath));
		ImageIO.write(bufferImg, "png", byteArrayOut);

		InputStream is = new FileInputStream(filePath);
		XSSFWorkbook workbook = new XSSFWorkbook(is);
		Sheet sheet = workbook.getSheetAt(0);

		XSSFDrawing patri = (XSSFDrawing) sheet.createDrawingPatriarch();
		// col1,row1 开始单元格 列和行,从0下标开始
		// col2,row2 开始单元格 列和行,从1下标开始
		XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 255, 255, col1, row1, col2, row2);
		patri.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_PNG));

		OutputStream out = new FileOutputStream(filePath);
		workbook.write(out);

		out.flush();
		out.close();

		is.close();

		System.out.println("----insert pic success------");

	}
}

 

posted on 2020-02-25 16:03  dreamstar  阅读(986)  评论(0编辑  收藏  举报