使用Java代码向Excel中插入图片
引入POI依赖
这里使用的是POI工具包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
public void photo() {
FileOutputStream fileOut = null;
BufferedImage bufferImg = null;
try {
//先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray
ByteArrayOutputStream byteArrayOutput = new ByteArrayOutputStream();
bufferImg = ImageIO.read(new File("C:\\Users\\Pictures\\Saved Pictures\\test.jpg"));
ImageIO.write(bufferImg, "jpg", byteArrayOutput);
// 创建excel的工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
// 创建excel的工作表
HSSFSheet sheet = workbook.createSheet();
// 画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
// 第一个单元格的列(从0开始)
short firstC = 1;
// 第一个单元格的行(从0开始)
int firstR = 1;
// 最后一个单元格的列(从0开始)
short lastC = 2;
// 最后一个单元格的行(从0开始)
int lastR = 2;
// 第一个单元格内的x坐标
int dx1 = 2;
// 第一个单元格内的y坐标
int dy1 = 0;
// 最后一个单元格中的x坐标
int dx2 = 1023;
// 最后一个单元格中的y坐标
int dy2 = 254;
// 设置图片插入位置
HSSFClientAnchor anchor = new HSSFClientAnchor(dx1, dy1, dx2, dy2, firstC, firstR, lastC, lastR);
// 插入图片
patriarch.createPicture(anchor, workbook.addPicture(byteArrayOutput.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
// 生成Excel
File file = new File("C:\\Users\\Pictures\\Saved Pictures\\test.xls");
file.createNewFile();
fileOut = new FileOutputStream(file);
// 写入excel文件
workbook.write(fileOut);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileOut != null) {
try {
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}