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 { byteArrayOut = new ByteArrayOutputStream(); 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 patriarch = sheet.createDrawingPatriarch(); HSSFCreationHelper creationHelper = workbook.getCreationHelper(); HSSFClientAnchor clientAnchor = creationHelper.createClientAnchor(); clientAnchor.setCol1(columnNo); clientAnchor.setRow1(rowNo);
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); } }
}
|
注:在将图片添加到工作簿中时,必须将其存储为字节数组