java 導出blob圖片到excel


實現功能,導出當前頁面顯示員工的圖片,核心代碼已給出,僅供參考, 如需轉載請注明出處http://www.cnblogs.com/wangjianguang/p/7852060.html 

我這里一頁最多將50張圖片導出到excel中,花費時間大概2秒鍾,導出圖片做限制,主要也是為了性能考慮,

我暫時沒有好的辦法,因為我們一個頁面最多展示50條數據,如果用戶想導出100條數據,那只能點擊下一頁,然后點擊導出。。。要是大神路過,歡迎指導,感謝!

 

@SuppressWarnings("deprecation")
    @RequestMapping("export-employeeImage")
    public void exportEmployeeImage(ModelMap model, TrainerQuery  query,
            HttpServletRequest request,HSSFWorkbook workbook, HttpServletResponse response)
            throws NoSuchFieldException, SecurityException,
            IllegalStateException, ServletException, IOException,
            WriteException, SQLException {
            response.reset();
            
            response.setContentType("APPLICATION/vnd.ms-excel;charset=UTF-8");
            // 注意,如果去掉下面一行代碼中的attachment; 那么也會使IE自動打開文件。
            response.setHeader(
                    "Content-Disposition",
                    "attachment; filename="
                            + java.net.URLEncoder.encode(
                                    "employeePhoto"+DateUtil.getExportDate()+".xls", "UTF-8"));
            OutputStream os = response.getOutputStream();
            String logoRealPathDir =request.getSession().getServletContext().getRealPath("//modile//employee-photo.xlsx");   //定義的模板,模板規則每行顯示5個,顯示6行,上下行間隔11個空格
            InputStream input_document = new FileInputStream(new File(logoRealPathDir));
            XSSFWorkbook input_work = new XSSFWorkbook(input_document);
            //-------------------begin導出圖片-----------------------------------
            XSSFSheet inpub_sheet = input_work.getSheetAt(0);
            
            // 設置樣式
            XSSFCellStyle textStyle10 = input_work.createCellStyle();
            // 設置垂直居中
            textStyle10.setAlignment(HorizontalAlignment.CENTER);
            textStyle10.setVerticalAlignment((short) 1);
            // 設置細邊框
            textStyle10.setBorderBottom(BorderStyle.THIN);
            textStyle10.setBorderRight(BorderStyle.THIN);
            textStyle10.setWrapText(true);
            XSSFFont fontText2 = input_work.createFont();
            // 字體號碼
            fontText2.setFontHeightInPoints((short) 11);
            // 字體名稱
            fontText2.setFontName("微軟雅黑");
            textStyle10.setFont(fontText2);
            //為了防止速度過慢,我這里設置了只能下載當前頁的數據圖片,可根據實際需要調整
            query.setCurrentPage(query.getTxtcurrentPage());
            query.setPageSize(query.getTxtpageSize());
            query.setTotalItem(query.getTotal());
            List<Map> picture = trainerService.getLecturersPhotos(query); //查詢數據庫獲取圖片,可根據實際需要修改
            XSSFRow input_row = null;
            int rowNum=11;
            int colNum=0;
            int row1=2;
            int row2=10;
            for (int i = 0; i < picture.size(); i++) {
                Map map = (Map) picture.get(i);
//                if(rowNum%11==0){
                    input_row = inpub_sheet.getRow(rowNum);  //獲取excel行
//                }
                String trainCode = map.get("TRAINERCODE").toString();  //讀取數據
                String name = map.get("NAME").toString();
                input_row.getCell(colNum).setCellStyle(textStyle10);  //設置單元格格式
                input_row.getCell(colNum).setCellValue(trainCode+"-"+name);  //往單元格中填充內容
                BLOB blob = (BLOB) map.get("AVATAR");
                BufferedInputStream in =null;
                InputStream inStream = blob.getBinaryStream();  //得到流對象
                long nLen = blob.length();
                int nSize = (int) nLen;  
                byte[] data = new byte[nSize];
                inStream.read(data);
                data=ImageHepler.ChangeImgSize(data,130,160);  //將讀取數據流轉換成圖片,並設置大小
                inStream = new ByteArrayInputStream(data);
                try {
                    in = new BufferedInputStream(inStream,1024);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                int pictureIdx =input_work.addPicture(in, input_work.PICTURE_TYPE_JPEG);//向excel中插入圖片
                XSSFDrawing drawing = inpub_sheet.createDrawingPatriarch();  //創建繪圖對象
               //   XSSFClientAnchor的參數說明:    
                 //   參數   說明    
                 //  dx1  第1個單元格中x軸的偏移量     
                 //  dy1  第1個單元格中y軸的偏移量     
                 //  dx2     第2個單元格中x軸的偏移量     
                 //  dy2  第2個單元格中y軸的偏移量    
                 //  col1 第1個單元格的列號     
                 //  row1  第1個單元格的行號     
                 //  col2 第2個單元格的列號     
                 //  row2 第2個單元格的行號     
                XSSFClientAnchor anchor= new XSSFClientAnchor(1, 1, 1, 1,(short) colNum, row1, (short) colNum+1, row2);//定位圖片的位置
                XSSFPicture pict = drawing.createPicture(anchor, pictureIdx); 
                response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
                pict.resize();
                colNum=colNum+3;
                if(colNum==15){
                    colNum=0;
                    rowNum=rowNum+13;
                    row1=row1+13;
                    row2=row2+13;
                }
            }
        try {
            input_work.write(os);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
package common.image.util;


import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import java.io.IOException;


import javax.imageio.ImageIO;

public class ImageHepler
{
 
  /**
     * 圖片轉換,將讀取圖片放大或縮小
     * 
     * */
    public static  byte[] ChangeImgSize(byte[] data, int nw, int nh){     
        byte[] newdata = null;     
        try{      
             BufferedImage bis = ImageIO.read(new ByteArrayInputStream(data));     
                int w = bis.getWidth();     
                int h = bis.getHeight();     
                double sx = (double) nw / w;     
                double sy = (double) nh / h;     
                AffineTransform transform = new AffineTransform();     
                transform.setToScale(sx, sy);     
                AffineTransformOp ato = new AffineTransformOp(transform, null);     
                //原始顏色     
                BufferedImage bid = new BufferedImage(nw, nh, BufferedImage.TYPE_3BYTE_BGR);     
                ato.filter(bis, bid);     
                //轉換成byte字節     
                ByteArrayOutputStream baos = new ByteArrayOutputStream();     
                ImageIO.write(bid, "jpeg", baos);     
                newdata = baos.toByteArray();     
        }catch(IOException e){      
             e.printStackTrace();      
        }      
        return newdata;     
    }    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM