文章目录
POI操作EXCEL插入图片
依赖
xml
<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中
java
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);
}
}
}
注:在将图片添加到工作簿中时,必须将其存储为字节数组
参考文献