我正在制作一个应用程序,将我们的数据结构转换为 Excel 文件。我们目前正在使用 POI 进行转换。
问题是Cell只支持字符串、数字和公式,而我们的数据结构支持图像。有没有办法向单元格添加图像?
Excel中没有图像单元格,您需要将图像添加到工作表中。
HSSFWorkbook workbook;
workbook.addPicture(pngData, HSSFWorkbook.PICTURE_TYPE_PNG);
这就是我使用 Apache POI 将图像添加到 Excel 工作簿的方法
try {
InputStream imageStream = new FileInputStream(image.getFile());
byte[] imageBytes = IOUtils.toByteArray(imageStream);
String extension = DocumentUtil.getFileExtension(image.getFile().getAbsolutePath());
int pictureTypeId = getWorkbookPictureTypeId(extension);
int pictureId = workbook.addPicture(imageBytes, pictureTypeId);
XSSFDrawing drawing = (XSSFDrawing) sheet.createDrawingPatriarch();
XSSFClientAnchor imageAnchor = new XSSFClientAnchor();
imageAnchor.setCol1(cell.getColumnIndex());
imageAnchor.setCol2(cell.getColumnIndex()+1);
imageAnchor.setRow1(cell.getRowIndex());
imageAnchor.setRow2(cell.getRowIndex()+1);
XSSFPicture excelImage = drawing.createPicture(imageAnchor, pictureId);
//get image width and height to adjust the cell row.
Double height = excelImage.getImageDimension().getHeight();
short heightInShort = height.shortValue();
short EmuUnitInShort = image.getHeight().shortValue();
cell.getRow().setHeight((short)(heightInShort*EmuUnitInShort));
} catch(Exception e) {
log.error(e.getMessage(), e);
}