0%

POI操作EXCEL插入图片

POI操作EXCEL插入图片

依赖

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>

使用HSSFPatriarch来将图片写入EXCEL中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
BufferedImage bufferImg;//图片
ByteArrayOutputStream byteArrayOut = null;
try {
// 先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray
byteArrayOut = new ByteArrayOutputStream();
//将图片读到BufferedImage
InputStream resource = Thread.currentThread().getContextClassLoader().getResourceAsStream(imageName);
if(resource == null){
throw new BusinessException("%s资源不存在",imageName);
}
bufferImg = ImageIO.read(resource);
// 将图片写入流中
ImageIO.write(bufferImg, "png", byteArrayOut);

// 利用HSSFPatriarch将图片写入EXCEL
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
// 定义单元格位置
HSSFCreationHelper creationHelper = workbook.getCreationHelper();
HSSFClientAnchor clientAnchor = creationHelper.createClientAnchor();
clientAnchor.setCol1(columnNo);
clientAnchor.setRow1(rowNo);


// 插入图片 PICTURE_TYPE_PNG是图片的类型
HSSFPicture picture = patriarch.createPicture(clientAnchor, workbook.addPicture(byteArrayOut
.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
picture.resize(2.5);

} catch (IOException e) {
LOGGER.error("图片写入excel失败", e);
} finally {
if (byteArrayOut != null) {
try {
byteArrayOut.close();
} catch (IOException e) {
LOGGER.error("关闭流失败", e);
}
}

}

注:在将图片添加到工作簿中时,必须将其存储为字节数组

欢迎关注我的其它发布渠道