记录POI获取excel中获取单元格内图片的数据和位置

/**
     * 获取图片和位置 (xlsx)
     */
    public static Map<String, String> getPictures2(XSSFSheet sheet) throws Exception {
        Map<String, String> map = new HashMap<>(16);
        List<POIXMLDocumentPart> list = sheet.getRelations();
        for (POIXMLDocumentPart part : list) {
            if (part instanceof XSSFDrawing) {
                XSSFDrawing drawing = (XSSFDrawing) part;
                List<XSSFShape> shapes = drawing.getShapes();
                for (XSSFShape shape : shapes) {
                    XSSFPicture picture = (XSSFPicture) shape;
                    // 会有空指针问题
                    // XSSFClientAnchor anchor = picture.getPreferredSize();
                    XSSFClientAnchor anchor = (XSSFClientAnchor) shape.getAnchor();
                    CTMarker marker = anchor.getFrom();
                    String key = marker.getRow() + "-" + marker.getCol();
                    String imgName = "lihang/lihang_picture_".concat(System.currentTimeMillis() + ".png");
                    String url = OssUtils.uploadToOss(picture.getPictureData().getData(), imgName, 1L);
                    map.put(key, url);
                }
            }
        }
        return map;
    }

    /**
     * 获取图片和位置 (xls)
     */
    public static Map<String, String> getPictures1(HSSFSheet sheet) throws Exception {
        Map<String, String> map = new HashMap<>(16);
        List<HSSFShape> list = sheet.getDrawingPatriarch().getChildren();
        for (HSSFShape shape : list) {
            if (shape instanceof HSSFPicture) {
                HSSFPicture picture = (HSSFPicture) shape;
                HSSFClientAnchor cAnchor = (HSSFClientAnchor) picture.getAnchor();
                // 行号-列号
                String key = cAnchor.getRow1() + "-" + cAnchor.getCol1();
                String imgName = "lihang/lihang_picture_".concat(System.currentTimeMillis() + ".png");
                String url = OssUtils.uploadToOss(picture.getPictureData().getData(), imgName, 1L);
                map.put(key, url);
            }
        }
        return map;
    }

  

posted @ 2021-08-31 17:07  也算知书识礼人  阅读(1169)  评论(0编辑  收藏  举报