使用Apache POI将列中的图像插入到Excel中

时间:2015-01-30 14:31:27

标签: java apache apache-poi

我试图将图像插入excel中的单元格。我添加了很好的图片,但我仍然在任何地方运行。我想说我想要这个专栏。

1 个答案:

答案 0 :(得分:15)

您可以先设置行和列,然后设置图像。

try {

   Workbook workbook = new XSSFWorkbook();
   Sheet sheet = workbook.createSheet("MYSheet");


   InputStream inputStream = new FileInputStream("path_to_image.jpg");

   byte[] imageBytes = IOUtils.toByteArray(inputStream);

   int pictureureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);

   inputStream.close();

   CreationHelper helper = workbook.getCreationHelper();

   Drawing drawing = sheet.createDrawingPatriarch();

   ClientAnchor anchor = helper.createClientAnchor();

   anchor.setCol1(1);
   anchor.setRow1(2);

   drawing.createPicture(anchor, pictureureIdx);


   FileOutputStream fileOut = null;
   fileOut = new FileOutputStream("output.xlsx");
   workbook.write(fileOut);
   fileOut.close();
}catch (Exception e) {
   System.out.println(e);
}