编程语言
首页 > 编程语言> > JAVA POI Excel 导出图片

JAVA POI Excel 导出图片

作者:互联网

public class ExcelUtils {
    public static void main(String[] args) throws IOException {
        FileOutputStream fileOut = null;
        //先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray
        String imgUrl = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2.3lian.com%2F2014cf%2Ff2%2F59%2Fd%2F103.jpg";
        URL url = new URL(imgUrl);
        //获取文件后缀名
        String suffix = imgUrl.substring(imgUrl.lastIndexOf(".") + 1);
        BufferedImage bufferImg = ImageIO.read(url);

        //注意:以本地的方式图片、注释上面四行有效代码 换成下面两行
        //        BufferedImage bufferImg = null;
        //        bufferImg = ImageIO.read(new File("D:/test.jpg"));

        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();


//        String suffix = (String) list.get(0).get("imgtype");
//        byte[] bytes = input2byte(list.get(0).getInputStream());
//        BufferedImage bufferImg = ImageIO.read(new ByteArrayInputStream(bytes));
//        if ("png".equals(suffix) || "PNG".equals(suffix) ) {
//            ImageIO.write(bufferImg, "png", byteArrayOut);
//        }else if("jpg".equals(suffix) || "JPG".equals(suffix)){
//            ImageIO.write(bufferImg, "jpg", byteArrayOut);
//        }else{
//            continue;
//        }

        //这里要注意formatName要缓存后缀名
        ImageIO.write(bufferImg, suffix, byteArrayOut);

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet1 = workbook.createSheet("test picture");
        sheet1.setDefaultColumnWidth((short)20);
        sheet1.setDefaultRowHeight((short)2000);

        //画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)
        HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();
        for(int i =0;i<10;i++){
            // 判断下一张图片位置
            // anchor主要用于设置图片的属性
            //    * 前四个参数是控制图片在单元格的位置,分别是图片距离单元格left,top,right,bottom的像素距离
            HSSFClientAnchor anchor =
                    new HSSFClientAnchor
                            (        0, //x缩放
                                    0, // y缩放
                                    1023, //最大1023
                                    255, //最大255
                                    (short) 4,  //于下下个参数进行定位 0开始
                                    i, //在第几行
                                    (short) 4, //宽度占几格 0开始
                                    i //第几列
                            );
//          anchor.setAnchorType(3);
            //插入图片
            patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));

        }
        fileOut = new FileOutputStream("D:/测试Excel.xls");
        // 写入excel文件
        workbook.write(fileOut);
        System.out.println("----Excel文件已生成------");
    }
}

 

标签:bufferImg,byteArrayOut,JAVA,suffix,Excel,new,POI,ImageIO,String
来源: https://www.cnblogs.com/juquanyu-com/p/15849577.html