画像をエクセル表にエクスポートします。

38345 ワード

需要の説明
先日は、公衆番号の中のユーザが送った写真をエクセル表にエクスポートしたいです。ここで記録します。ユーザーが公衆番号に画像を送信すると、マイクロメッセージは開発者に関連するデータ、例えば、オプンド、タイプ、写真アドレスなどにプッシュされます。私がしたいのは、画像のアドレスを取得し、WeChatにアクセスし、画像を取得し、ファイルに書き込むことです。
ツールクラス
/**
String[] rowsName :excel     
String fileName = "XXX" + ".xls";
pageList      list  
*/
public static HSSFWorkbook QdActivePictureExport(String[] rowsname, List<ActiveUserBean> pageList, String fileName) {
        logger.info("START:---    ");
        //   excel  
        HSSFWorkbook workbook = new HSSFWorkbook();
        //        
        HSSFSheet sheet = workbook.createSheet("XXXX  ");
        //        ,  sheet      
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        /**
         *
         * 1.          2.      3.       ,       
         */
        String columContent[] = null;
        int rows = 0;//          
        //     
        //      
        HSSFRow row = sheet.createRow(rows);
        HSSFCell cell = null;
        for (int i = 0; i < rowsname.length; i++) {
            cell = row.createCell(i);
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(rowsname[i]);
        }
        int pageSize = pageList.size();
        if (pageList != null && pageSize > 0) {
            //       
            for (ActiveUserBean dff : pageList) {
                //        
                rows++;
                //      
                row = sheet.createRow(rows);
                //      
                //todo      
                cell = row.createCell(0);
                cell.setCellValue(dff.getFrom_user_name());
                cell = row.createCell(1);
                cell.setCellValue(dff.getCity_code());
                cell = row.createCell(2);
                cell.setCellValue(dff.getCreate_time());
                cell = row.createCell(3);
                cell.setCellValue(dff.getMsg_type());
                cell = row.createCell(4);
                //cell.setCellValue(dff.getContent1());
                intoPic(dff.getContent1(), fileName, workbook, sheet, patriarch, row, rows, pageSize);
               
            }
        }
        return workbook;
    }

  • intoPic()方法は、ioストリームで
  • を導出する。
    
    public static void intoPic(String pictureUrl, String filename, HSSFWorkbook workbook, HSSFSheet sheet,
                                   HSSFPatriarch patriarch, HSSFRow row, int rows, int pageSize) {
            FileOutputStream fileOut = null;
            logger.info("      :" + pictureUrl + "__filename:" + filename + "__rows:" + rows);
            try {
           
                //todo       
                sheet.setColumnWidth(4, 256 * 50 + 184);
                row.setHeight((short) 1000);
    
                //     
                String replaceUrl = pictureUrl.replace("http://", "http://www.XXXX.com/XXXX/");
                URL url = new URL(replaceUrl);
    
                //    
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //       "GET"
                conn.setRequestMethod("GET");
                //       5 
                conn.setConnectTimeout(5 * 1000);
                //           
                InputStream inStream = conn.getInputStream();
               
                //          ,          ,     
                byte[] data = readInputStream(inStream);
    
                //anchor             todo row1 row2         
                HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 4, rows, (short) 4, rows);
                //(         )
                //0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells.
                anchor.setAnchorType(3);
                patriarch.createPicture(anchor, workbook.addPicture(data, HSSFWorkbook.PICTURE_TYPE_JPEG));
              
                fileOut = new FileOutputStream(filename);
              
                //   excel  
                workbook.write(fileOut);
                logger.info("        ");
    
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("  :"+e);
            } finally {
                    if (fileOut != null) {
                        try {
                            fileOut.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                            logger.info("finally  !");
                        }
                }
            }
    
        }
    
    	//todo    
        private static byte[] readInputStream(InputStream inStream) throws IOException {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            //    Buffer   
            byte[] buffer = new byte[1024 * 8];
            //          ,   -1,        
            int len = 0;
            //        buffer        
            while ((len = inStream.read(buffer)) != -1) {
                //     buffer     ,              ,len       
                outStream.write(buffer, 0, len);
            }
            //     
            inStream.close();
            // outStream        
            return outStream.toByteArray();
        }
    
  • は、ローカル
  • に導出される。
    //          HSSFWorkbook workbook
     QdActiveOutExcelUtil.write(response,fileName,workbook);
     
     /**
         *       
         *
         * @param response
         * @param fileName
         * @param workbook
         * @throws IOException
         */
        public static void write(HttpServletResponse response, String fileName, HSSFWorkbook workbook) throws IOException {
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + Encodes.urlEncode(fileName));
            workbook.write(response.getOutputStream());
        }
    
    ローカルテストクラス
    	@Test
        public void test3() throws IOException {
            FileOutputStream fileOut = null;
            try {
                //String befor = "E:\\zsl\\picture\\28314.jpg";
    
                //      
                HSSFWorkbook wb = new HSSFWorkbook();
                HSSFSheet sheet = wb.createSheet("      ");
                HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
                //todo     
                HSSFRow row = sheet.createRow(3);
    
                //sheet.setColumnWidth( 100,  100);
                //todo    
                sheet.setColumnWidth(5, 256 * 50 + 184);
                row.setHeight((short) 1000);
    
                //todo     
                String pictureUrl = weixin    ";
    
                URL url = new URL(pictureUrl);
                //    
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //       "GET"
                conn.setRequestMethod("GET");
                //       5 
                conn.setConnectTimeout(5 * 1000);
                //           
                InputStream inStream = conn.getInputStream();
    
                //    
                //BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(befor));
                //          ,          ,     
                byte[] data = readInputStream(inStream);
    
                //anchor            todo         row1,row2            
                HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 5, 3, (short) 5, 3);
                //(         )
                //0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells.
                anchor.setAnchorType(0);
                patriarch.createPicture(anchor, wb.addPicture(data, HSSFWorkbook.PICTURE_TYPE_JPEG));
                //String name = " Excel.xls";
                fileOut = new FileOutputStream("E:/ 4Excel.xls");
                //fileOut = new FileOutputStream(name);
                //   excel  
                wb.write(fileOut);
                System.out.println("----Excle3     ------");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fileOut != null) {
                    try {
                        fileOut.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
    画像をエクスポートするときはセルのサイズが設定されていますが、画像はどのセル内にあるかに注意が必要です。