Get an image and its position from excel file using Apache POI

前端 未结 3 1592
日久生厌
日久生厌 2020-12-20 17:21

Is it possible to extract an image\'s information from an xls spreadsheet using Apache POI?

In one of my projects, I need to read some images from a .xls file. I can

相关标签:
3条回答
  • 2020-12-20 17:54

    Have a look here:

    http://poi.apache.org/components/spreadsheet/quick-guide.html#Images

    Sample:

    List lst = workbook.getAllPictures();
    
    for (Iterator it = lst.iterator(); it.hasNext(); ) {
    
        PictureData pict = (PictureData)it.next();
    
        String ext = pict.suggestFileExtension();
    
        byte[] data = pict.getData();
    
        if (ext.equals("jpeg")) {
    
          FileOutputStream out = new FileOutputStream("pict.jpg");
    
          out.write(data);
    
          out.close();
    
        }
    }
    

    After this, you can use tools like ImageInfo which extends Magick to find out various configs. Yo can even convert images to different sizes.

    Take a look at this class as well:

    http://blog.jaimon.co.uk/simpleimageinfo/SimpleImageInfo.java.html

    -- Hope this helps

    0 讨论(0)
  • 2020-12-20 17:58

    And if you don`t want to use iterator (cause some times they are heavy)

    public List readDrawing(Workbook workbook) throws Exception {
        List list = workbook.getAllPictures();
    
        for (int i=0; i<list.size(); i++) {
            PictureData picture = (PictureData) list.get(i);
    
            String ext = picture.suggestFileExtension();
            byte[] data = picture.getData();
    
            FileOutputStream out = new FileOutputStream("imageName" + "." + ext);
            out.write(data);
            out.close();
        }
    
        return list;
    }
    
    0 讨论(0)
  • 2020-12-20 18:15

    I hope this code will help)

        XSSFDrawing dp = workbook.getSheetAt(1).createDrawingPatriarch();
        List<XSSFShape> pics = dp.getShapes();
        XSSFPicture inpPic = (XSSFPicture)pics.get(0);
    
        XSSFClientAnchor clientAnchor = inpPic.getClientAnchor();
        inpPic.getShapeName(); // узнаю название картинки
        PictureData pict = inpPic.getPictureData();
        FileOutputStream out = new FileOutputStream("pict.jpg");
        byte[] data = pict.getData();
        out.write(data);
        out.close();
        System.out.println("col1: " + clientAnchor.getCol1() + ", col2: " + clientAnchor.getCol2() + ", row1: " + clientAnchor.getRow1() + ", row2: " + clientAnchor.getRow2());
        System.out.println("x1: " + clientAnchor.getDx1() + ", x2: " + clientAnchor.getDx2() +  ", y1: " + clientAnchor.getDy1() +  ", y2: " + clientAnchor.getDy2());
    
    0 讨论(0)
提交回复
热议问题