简体   繁体   中英

Insert image in column to excel using Apache POI

I'm trying to insert an image into a cell in excel. I've added pictures fine, but I still runs anywhere. I want to say that I want this column.

You can set the row and column first then set the image.

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);
}

I had some problems positioning image inside excel sheet. Here is the code which worked for me (Microsoft Excel 2019 version 2110)

public static void main(String[] args) throws IOException {
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet();

    Path imagePath = Path.of("...path to your image...");
    byte[] imageContent = Files.readAllBytes(imagePath);

    int pictureIndex = workbook.addPicture(imageContent, Workbook.PICTURE_TYPE_PNG);
    // Option 1: use constructor, parameters 5-8 define starting cell-row and ending cell-row for image position
    // I have no clue what first 4 parameters are doing
    XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 3, 3, 6, 12);

    // Option 2: use Creation Helper and setters for defining starting and ending cell
    XSSFClientAnchor anchor = workbook.getCreationHelper().createClientAnchor();
    anchor.setCol1(3);
    anchor.setRow1(3);
    anchor.setCol2(6);
    anchor.setRow1(12);

    XSSFDrawing drawingPatriarch = sheet.createDrawingPatriarch();
    drawingPatriarch.createPicture(anchor, pictureIndex);

    workbook.write(new FileOutputStream("output.xlsx"));
}

Maven dependency

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.1.0</version>
</dependency>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM