简体   繁体   English

使用 Apache POI 在列中插入图像以提高性能

[英]Insert image in column to excel using Apache POI

I'm trying to insert an image into a cell in excel.我正在尝试将图像插入 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.我在 Excel 表格中定位图像时遇到了一些问题。 Here is the code which worked for me (Microsoft Excel 2019 version 2110)这是对我有用的代码(Microsoft Excel 2019 版本 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 Maven 依赖

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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