POI導出圖片到excel

1.需求: 導出圖片到excel中

2. 問題:圖片是存在圖片服務器上,不能直接像讀取本地圖片那樣讀取圖片

3.  解決方案參考網上

 //  插入圖片
        String shopPic = storeFindVo.getShopPic();
        int num = 0;
        if (shopPic != null){
            //獲取服務器地址
            String filePath = SystemConstants.getPtdImageUrl();
            String[] picList = shopPic.split(",");
            for (int i=0;i<picList.length;i++){
                try {
                    byte[] data = {};
                    URL url = new URL(filePath + picList[i]);
                    //打開連接
                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                    //設置請求方式爲"GET"
                    conn.setRequestMethod("GET");
                    //超時響應時間爲5秒
                    conn.setConnectTimeout(5 * 1000);
                    //通過輸入流獲取圖片數據
                    InputStream inStream = conn.getInputStream();
                    data = readInputStream(inStream);
                    if (i == 0){
                        exportMap.put("shopPic",data);
                    }else{
                        exportMap.put(""+num,data);
                        if (!arrayList.contains(""+num)){
                            arrayList.add(""+num);
                        }
                    }
                    num ++;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }else {
            exportMap.put("shopPic","");
        }
private static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //創建一個Buffer字符串
        byte[] buffer = new byte[1024];
        //每次讀取的字符串長度,如果爲-1,代表全部讀取完畢
        int len = 0;
        //使用一個輸入流從buffer裏把數據讀取出來
        while( (len=inStream.read(buffer)) != -1 ){
            //用輸出流往buffer裏寫入數據,中間參數代表從哪個位置開始讀,len代表讀取的長度
            outStream.write(buffer, 0, len);
        }
        //關閉輸入流
        inStream.close();
        //把outStream裏的數據寫入內存
        return outStream.toByteArray();
    }

4.效果如下

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章