exl表格导出(带有图片导出)

如题 废话不多 直接上代码

/**
 * @author: 骑猪撞地球QAQ
 * @date: 2020/10/27 13:51
 * @content:
 */
public class DataExportXls {
    
    

    /**
     * 数据导出
     *
     * @param queryVo  查询参数
     * @param flag     是否导出图片 1:不导出;  非1均为导出
     * @param request
     * @param response
     */
    public void exportXls(QueryVo queryVo, Integer flag, HttpServletRequest request,
                          HttpServletResponse response) {
    
    
        Page page = new Page("1", "50000");
        // 查询数据获取到需要导出的结果集
        List<DetailVo> result = pageInfo.getList();
        try {
    
    
            //内存中缓存记录行数
            int rowaccess = 100;
            SXSSFWorkbook wb = new SXSSFWorkbook(rowaccess);
            // sheet最大行数
            int maxRowNums = 50000;
            int sheetNum = result.size() / maxRowNums + 1;
            Sheet[] sheets = new Sheet[sheetNum];
            CellStyle headerStyle = wb.createCellStyle();
            headerStyle.setAlignment(HorizontalAlignment.CENTER);
            headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            headerStyle.setWrapText(true);
            Font font = wb.createFont();
            font.setFontName("宋体");//设置字体
            font.setFontHeightInPoints((short) 14);//设置字体大小
            font.setBold(true);//粗体显示
            headerStyle.setFont(font);
            for (int i = 0; i < sheets.length; i++) {
    
    
                // 创建Excel的工作sheet,对应到一个excel文档的tab
                sheets[i] = wb.createSheet("数据查看" + (i + 1));
                Row rowTitle = sheets[i].createRow(0);
                Cell cell0 = rowTitle.createCell((short) 0);
                cell0.setCellStyle(headerStyle);
                cell0.setCellValue("第一列");
                Cell cell1 = rowTitle.createCell((short) 1);
                cell1.setCellStyle(headerStyle);
                cell1.setCellValue("第二列");
                Cell cell2 = rowTitle.createCell((short) 2);
                cell2.setCellStyle(headerStyle);
                cell2.setCellValue("第三列");
                Cell cell3 = rowTitle.createCell((short) 3);
                cell3.setCellStyle(headerStyle);
                cell3.setCellValue("第四列");
                Cell cell4 = rowTitle.createCell((short) 4);
                cell4.setCellStyle(headerStyle);
                cell4.setCellValue("第五列");
                Cell cell5 = rowTitle.createCell((short) 5);
                cell5.setCellStyle(headerStyle);
                cell5.setCellValue("第六列");
                Cell cell6 = rowTitle.createCell((short) 6);
                cell6.setCellStyle(headerStyle);
                cell6.setCellValue("图片");
            }
            for (int i = 0; i < result.size(); i++) {
    
    
                int j = i / maxRowNums;
                DetailVo s = result.get(i);
                Row row = sheets[j].createRow(i % maxRowNums + 1);
                row.setHeight((short) 2000);
                BufferedImage bufferImg = null;
                //先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray
                //画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)
                Drawing patriarch = sheets[j].createDrawingPatriarch();
                row.createCell((short) 1);
                Cell cell0 = row.createCell((short) 0);
                cell0.setCellValue(s.getEmployeeName());
                Cell cell1 = row.createCell((short) 1);
                cell1.setCellValue(s.getPositionName());
                Cell cell2 = row.createCell((short) 2);
                cell2.setCellValue(s.getOrgName());
                Cell cell3 = row.createCell((short) 3);
                cell3.setCellValue(s.getDate());
                Cell cell4 = row.createCell((short) 4);
                cell4.setCellValue(s.getType());
                Cell cell5 = row.createCell((short) 5);
                cell5.setCellValue(s.getGroupName());

                // 获取照片并且处理
                List<PicVo> picList = getPicListByBusinessIdAndType(s.getId(), s.getType());
                if (CollectionUtil.listNotEmptyNotSizeZero(picList)) {
    
    
                    for (int k = 0; k < picList.size(); k++) {
    
    
                        PicVo picVo = picList.get(k);
                        if (flag != null && flag.equals(1)) {
    
    
                            // 等于 1 则不导出
                            if (StringUtil.isBlank(s.getSignPic())) {
    
    
                                Cell cell6 = row.createCell((short) 6);
                                cell6.setCellValue("");
                            } else {
    
    
                                setPicture(wb, bufferImg, row, patriarch, picVo.getUrlPath(), i, k);
                            }
                        }
                    }
                }
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String filename = "导出记录" + sdf.format(new Date()) + ExcelTypeEnum.XLSX.getValue();// 设置下载时客户端Excel的名称
            if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
    
    
                filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");// firefox浏览器
            } else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0
                    || request.getHeader("User-Agent").toUpperCase().indexOf("TRIDENT") > 0
                    || request.getHeader("User-Agent").toUpperCase().indexOf("EDGE") > 0) {
    
    
                filename = URLEncoder.encode(filename, "UTF-8");// IE浏览器
            } else if (request.getHeader("User-Agent").toUpperCase().indexOf("CHROME") > 0) {
    
    
                filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");// 谷歌
            }
            response.setContentType("applicationnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            // 需注意 关闭流不应该在这里  此处需优化  只是写了个demo   
            os.close();
        } catch (Exception e) {
    
    
            log.error(e.getMessage());
        }
    }


    /**
     * 设置图片
     *
     * @param wb
     * @param bufferImg
     * @param row
     * @param patriarch
     * @param path
     * @param i
     */
    private void setPicture(SXSSFWorkbook wb, BufferedImage bufferImg, Row row, Drawing patriarch, String path, int i, int k) {
    
    
        XSSFClientAnchor anchor = null;
        if (StringUtil.isBlank(path)) {
    
    
            Cell cell10 = row.createCell((short) 10);
            cell10.setCellValue("");
        } else {
    
    
            try {
    
    
                URL url = new URL(path);
                bufferImg = ImageIO.read(url);
                ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                ImageIO.write(bufferImg, "jpg", byteArrayOut);
                // anchor主要用于设置图片的属性  此处可以调图片的展示位置  具体按照自己情况而定
                anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) 12 + k, i + 1, (short) 13 + k, i + 2);
                anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_DONT_RESIZE);
                // 插入图片
                patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), Workbook.PICTURE_TYPE_JPEG));
            } catch (Exception e) {
    
    
                log.error(e.getMessage());
            }
        }
    }
}

附 HSSFClientAnchor 参数说明

HSSFClientAnchor用于创建一个新的端锚,并设置锚的左下和右下坐标,用于图片插入/画线等等。

HSSFClientAnchor(int dx1, int dy1, int dx2, int dy2, short col1, int row1, short col2, int row2)

dx1 dy1 起始单元格中的x,y坐标.

dx2 dy2 结束单元格中的x,y坐标

col1,row1 指定起始的单元格,下标从0开始

col2,row2 指定结束的单元格 ,下标从0开始

猜你喜欢

转载自blog.csdn.net/weixin_44974020/article/details/116260593