java导入excel图片处理

直接看代码吧,主要逻辑吧excel的图片拿到 压缩上传获取url

 // 将文件转成XSSFWorkbook工作簿
        XSSFWorkbook wb = new XSSFWorkbook(uploadFile);
        // 获取工作薄中第一个excel表格
        XSSFSheet sheet = wb.getSheetAt(0);
        // 核心:::获取excel表格中所有图片,处理图片上传到oss  key:行号-列号
        Map<String, List<String>> picturesMap = getPictures(sheet);
        public Map<String, List<String>> getPictures(XSSFSheet xssfSheet) throws IOException {

        Map<String, List<String>> maps = new LinkedHashMap<>();
        List<XSSFShape> list = xssfSheet.getDrawingPatriarch().getShapes();

        for (int i = 0; i < list.size(); i++) {
            XSSFPicture picture = (XSSFPicture) list.get(i);
            // 行号-列号
            XSSFClientAnchor xssfClientAnchor = (XSSFClientAnchor) picture.getAnchor();
            // 获取图片
            XSSFPictureData pdata = picture.getPictureData();
            byte[] data = pdata.getData();
            InputStream inputStream = new ByteArrayInputStream(data);
            byte[] scalePicLater = scalePics(inputStream,0.5,0.5);
            String url = ossFactory.build().upload(new ByteArrayInputStream(scalePicLater), IdUtil.objectId() + ".jpg");
            inputStream.close();

            // 行号-列号
            String key = xssfClientAnchor.getRow1() - 1 + "-" + xssfClientAnchor.getCol1();
            if (maps.containsKey(key)) {
                List<String> strUrl = maps.get(key);
                strUrl.add(url);
                maps.put(key, strUrl);
            } else {
                List<String> strUrl = new ArrayList<>();
                strUrl.add(url);
                maps.put(key, strUrl);
            }


        }
        return maps;
    }




public static byte[] scalePics(InputStream inputStream, double accuracy,double scale) throws IOException {
        // 压缩图片并保存到临时文件中
        File tempFile = File.createTempFile("thumbnail", ".jpg");
        Thumbnails.of(inputStream)
                .scale(scale)
                .outputQuality(accuracy)
                .toFile(tempFile);
        // 读取临时文件的字节流设置到输出流中
        InputStream tempInputStream = new FileInputStream(tempFile);
        byte[] buffer = new byte[tempInputStream.available()];
        tempInputStream.read(buffer);
        tempInputStream.close();
        // 删除临时文件
        tempFile.delete();
        // 下载到本地,
        // BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:\\Code\\upload\\1.jpg"));
        // bos.write(buffer);
        // bos.close();
        return buffer;
    }

你可能感兴趣的:(java,excel)