1. 程式人生 > 實用技巧 >java匯出圖片到Excel,並通過瀏覽器下載Excel

java匯出圖片到Excel,並通過瀏覽器下載Excel

建立 Excel 表格

public void outExcel(Integer fileId, HttpServletResponse response){

        //根據檔案id查詢檔案物件
        XzFile file = xzFileMapper.getFileById(fileId);
        if (file==null || file.equals("")){
            return;
        }
        //建立工作簿物件
        HSSFWorkbook wb = new HSSFWorkbook();
        
//建立新的sheet物件(excel的表單) HSSFSheet sheet = wb.createSheet(file.getName());

//在sheet裡建立第一行,引數為行索引(excel的行),可以是0~65535之間的任何一個 HSSFRow row = sheet.createRow(0); //建立單元格(excel的單元格,引數為列索引,可以是0~255之間的任何一個 HSSFCell cell = row.createCell(0); //設定單元格的值 cell.setCellValue("登記卡");
//合併單元格CellRangeAddress構造引數依次表示起始行,截至行,起始列, 截至列 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6)); //多值判斷 CellIsWhatUtil cellIsWhatUtil = new CellIsWhatUtil(); //在sheet中建立第二行 HSSFRow row2 = sheet.createRow(1); //新增單元格中的內容 row2.createCell(0).setCellValue("姓名"); row2.createCell(
1).setCellValue(file.getName()); row2.createCell(2).setCellValue("性別"); row2.createCell(3).setCellValue(cellIsWhatUtil.isSex(file.getSex())); row2.createCell(4).setCellValue("聯絡方式"); row2.createCell(5).setCellValue(file.getMobile()); HSSFCell cell6 = row2.createCell(6); if (file.getIdPhoto() == null || file.getIdPhoto().equals("")) { cell6.setCellValue("貼相片處\n" + "(2寸白底)"); } else { // 利用HSSFPatriarch將圖片寫入EXCEL HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
//拿到圖片的二進位制資料   cellIsWhatUtil:圖片轉為二進位制工具類
            byte[] imgData = cellIsWhatUtil.getImgData(file.getIdPhoto());
            //anchor主要用於設定圖片的屬性
            HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 7, 1, (short) 6, 4);
            //Sets the anchor type (圖片在單元格的位置)
            //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, wb.addPicture(imgData, HSSFWorkbook.PICTURE_TYPE_JPEG));
        }


        sheet.addMergedRegion(new CellRangeAddress(1, 4, 6, 6));


        //在sheet中建立第3行
        HSSFRow row3 = sheet.createRow(2);
        //新增單元格中的內容
        row3.createCell(0).setCellValue("身份證號");
        row3.createCell(1).setCellValue(file.getPerId());
        row3.createCell(2).setCellValue("文化程度");
        row3.createCell(3).setCellValue(cellIsWhatUtil.isEdu(file.getEduDegree()));
        row3.createCell(4).setCellValue("民族");
        row3.createCell(5).setCellValue(file.getNation());


        //在sheet中建立第4行
        HSSFRow row4 = sheet.createRow(3);
        //新增單元格中的內容
        row4.createCell(0).setCellValue("入伍時間");
        row4.createCell(1).setCellValue(cellIsWhatUtil.timeToString(file.getEnlistmentTime()));
        row4.createCell(2).setCellValue("退役時間");
        row4.createCell(3).setCellValue(cellIsWhatUtil.timeToString(file.getRetirementTime()));
        row4.createCell(4).setCellValue("待遇批准時間");
        row4.createCell(5).setCellValue(cellIsWhatUtil.timeToString(file.getTreatmentTime()));
        //合併單元格CellRangeAddress構造引數依次表示起始行,截至行,起始列, 截至列
        sheet.addMergedRegion(new CellRangeAddress(4, 4, 3, 5));


        //在sheet中建立第5行
        HSSFRow row5 = sheet.createRow(4);
        //新增單元格中的內容
        row5.createCell(0).setCellValue("政治面貌");
        row5.createCell(1).setCellValue(cellIsWhatUtil.isGood(file.getPolOutlook()));
        row5.createCell(2).setCellValue("戶籍所在地");
        row5.createCell(3).setCellValue(file.getHometown());

        //在sheet中建立第6行
        HSSFRow row6 = sheet.createRow(5);
        //新增單元格中的內容
        row6.createCell(0).setCellValue("人員類別");
        row6.createCell(1).setCellValue(cellIsWhatUtil.isPer(file.getPerCategory(), file));
        //合併單元格CellRangeAddress構造引數依次表示起始行,截至行,起始列, 截至列
        sheet.addMergedRegion(new CellRangeAddress(5, 5, 1, 6));

        //在sheet中建立第7行
        HSSFRow row7 = sheet.createRow(6);
        //新增單元格中的內容
        row7.createCell(0).setCellValue("變更情況");
        row7.createCell(1).setCellValue(file.getChanges());
        //合併單元格CellRangeAddress構造引數依次表示起始行,截至行,起始列, 截至列
        sheet.addMergedRegion(new CellRangeAddress(6, 6, 1, 6));

        //在sheet中建立第8行
        HSSFRow row8 = sheet.createRow(7);
        //新增單元格中的內容
        row8.createCell(0).setCellValue("備註:");
        row8.createCell(1).setCellValue(file.getRemark());
        //合併單元格CellRangeAddress構造引數依次表示起始行,截至行,起始列, 截至列
        sheet.addMergedRegion(new CellRangeAddress(7, 7, 1, 6));


        //設定每行的高度
        row.setHeightInPoints(30);
        row2.setHeightInPoints(20);
        row3.setHeightInPoints(20);
        row4.setHeightInPoints(20);
        row5.setHeightInPoints(30);
        row6.setHeightInPoints(30);
        row7.setHeightInPoints(30);
        row8.setHeightInPoints(30);

        //設定每列的寬度
        int[] width = {3000, 3000, 3000, 3000, 3000, 3000, 3000};
        for (int i = 0; i < width.length; i++) {
            sheet.setColumnWidth(i, width[i]);
        }

        // row1
        HSSFCellStyle cellStyle = wb.createCellStyle();
        HSSFFont fontStyle = wb.createFont();
        /*//設定上下左右四個邊框寬度
        cellStyle.setBorderTop(HSSFBorderFormatting.BORDER_THIN);
        cellStyle.setBorderBottom(HSSFBorderFormatting.BORDER_THIN);
        cellStyle.setBorderLeft(HSSFBorderFormatting.BORDER_THIN);
        cellStyle.setBorderRight(HSSFBorderFormatting.BORDER_THIN);
        //設定上下左右四個邊框顏色
        cellStyle.setTopBorderColor(HSSFColor.RED.index);
        cellStyle.setBottomBorderColor(HSSFColor.RED.index);
        cellStyle.setLeftBorderColor(HSSFColor.RED.index);
        cellStyle.setRightBorderColor(HSSFColor.RED.index);*/
        //水平居中
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //垂直居中
        cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        //設定自動換行
        cellStyle.setWrapText(true);
        //設定字型樣式
        fontStyle.setFontName("宋體");
        //設定字型高度
        fontStyle.setFontHeightInPoints((short) 15);
        //設定字型顏色
        fontStyle.setColor(HSSFColor.BLACK.index);
        //設定粗體
        fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //設定斜體
//        fontStyle.setItalic(true);
        //設定下劃線
//        fontStyle.setUnderline(HSSFFont.U_SINGLE);
        //字型也是單元格格式的一部分,所以從屬於HSSFCellStyle
        // 將字型物件賦值給單元格樣式物件
        cellStyle.setFont(fontStyle);
        // 將單元格樣式應用於單元格
        cell.setCellStyle(cellStyle);


        // row2,3,4
        HSSFCellStyle cellStyle2 = wb.createCellStyle();
        HSSFFont fontStyle2 = wb.createFont();
        //水平居中
        cellStyle2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //垂直居中
        cellStyle2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        //設定自動換行
        cellStyle2.setWrapText(true);
        //設定字型樣式
        fontStyle2.setFontName("宋體");
        //設定字型高度
        fontStyle2.setFontHeightInPoints((short) 7);
        //設定字型顏色
        fontStyle2.setColor(HSSFColor.BLACK.index);
        //設定粗體
        fontStyle2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 將字型物件賦值給單元格樣式物件
        cellStyle2.setFont(fontStyle2);
        //第二行
        for (int i = 0; i < 7; i++) {
            row2.getCell(i).setCellStyle(cellStyle2);
        }
        //第三四行
        for (int i = 0; i < 6; i++) {
            row3.getCell(i).setCellStyle(cellStyle2);
            row4.getCell(i).setCellStyle(cellStyle2);
        }
        //第五行
        for (int i = 0; i < 4; i++) {
            row5.getCell(i).setCellStyle(cellStyle2);
        }
        //第6,7,8行
        for (int i = 0; i < 2; i++) {
            row6.getCell(i).setCellStyle(cellStyle2);
            row7.getCell(i).setCellStyle(cellStyle2);
            row8.getCell(i).setCellStyle(cellStyle2);
        }


        //輸出Excel檔案
//        FileOutputStream fileOutputStream = null;

        OutputStream output;
        try {
            output = response.getOutputStream();
            //清空快取
            response.reset();
            //定義瀏覽器響應表頭,順帶定義下載名,比如students(中文名需要轉義)
            String s = file.getName() + file.getBirthday();
            response.setHeader("Content-disposition", "attachment;filename=" + new String(s.getBytes(), "iso-8859-1") + ".xls");
            //定義下載的型別,標明是excel檔案
            response.setContentType("application/vnd.ms-excel");
            //這時候把建立好的excel寫入到輸出流
            wb.write(output);
            //養成好習慣,出門記得隨手關門
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

cellIsWhatUtil工具類:拿到圖片的二進位制資料

    public byte[] getImgData(String pictureUrl){
        if(StringUtils.isNotBlank(pictureUrl)) {
            if (pictureUrl==null || pictureUrl.equals("")){
                return null;
            }
      //圖片地址字首
            String str = "http://*****/temp/";

            //路徑有漢字需要轉碼    String url = “http://l****/test?condition=”+URLEncoder.encode("工廠","utf-8");
            int i = pictureUrl.lastIndexOf("/");
            String substring = pictureUrl.substring(i+1);

            URL url = null;
            try {
                url = new URL(str+ URLEncoder.encode(substring,"utf-8"));
                //開啟連結
                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                //設定請求方式為"GET"
                conn.setRequestMethod("GET");
                //超時響應時間為5秒
                conn.setConnectTimeout(5 * 1000);
                //通過輸入流獲取圖片資料
                InputStream inStream = conn.getInputStream();
                //得到圖片的二進位制資料,以二進位制封裝得到資料,具有通用性
                byte[] data = readInputStream(inStream);// 得到圖片的二進位制資料
                return data;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }