Get picture position in Apache POI from Excel xls

2019-07-12 02:12发布

问题:

My need is to get a picture data as bytes, then it's anchor details and finaly display the result on screen at target position and size for my users...

The API shows we can get a list of all pictures through workbook object like this:

List<HSSFPictureData> picturesData = workbook.getAllPictures();

and also we are able to fetch all anchors details (see HSSFClientAnchor details here).

Problem is HSSFPicture.getPictureIndex() refered by an anchor does not match HSSFPictureData collection index of getAllPictures() method above...

...now the question is: how to map HSSFClientAnchor instances to specific HSSFPictureData instances or the opposite?

回答1:

List<HSSFShape> shapes  = this.tSheet.sheet().getDrawingPatriarch().getChildren();
        for (int i = 0; i < shapes.size(); i++)
        {
            if(shapes.get(i) instanceof HSSFPicture)
            {   
                HSSFPicture pic = (HSSFPicture) shapes.get(i);
                HSSFPictureData picdata = this.tSheet.sheet().getWorkbook().getAllPictures().get(pic.getPictureIndex());
                int pictureIndex = this.newSheet.getWorkbook().addPicture( picdata.getData(), picdata.getFormat());

this.newSheet.createDrawingPatriarch().createPicture((HSSFClientAnchor)pic.getAnchor()r, pictureIndex);

            }


        }

NOTE: Above code will read pic data from one sheet to another sheet this.tSheet.sheet() is source sheet this.newSheet is new sheet