POI导出实现以及导出所有图片都是第一次插入图片解决办法

本文介绍如何使用Java的POI库导出文件,并解决在导出过程中图片总是显示为第一次插入时的图片的问题,提供了详细的导出代码和解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

POI导出实现以及导出所有图片都是第一次插入图片解决办法

导出代码

    @ResponseBody
    @ApiOperation(value = "导出", httpMethod = "GET")
    public Result export(HttpServletResponse response, @RequestParam("list") List<EquipmentContrastDTO> list) {
        
        List<String> nameList; // 这里是我业务需要动态表头
        if (CollectionUtils.isEmpty(list)) { //list 是导出数据
            return Result.success("导出成功");
        }

        //导出的标题
        List<String> title = new ArrayList<>();
        title.add("名称");
        title.add("图片");
        if (CollectionUtils.isNotEmpty(list.get(0).getFdEquipmentParameterList())) {
            nameList = list.get(0).getFdEquipmentParameterList().stream().map(name -> name.getParameterName()).collect(Collectors.toList());
        	title.addAll(nameList);
        }
        //excel名称
        String fileName = "导出.xlsx";
        //sheet名称
        String sheetName = "sheet名称";
        //调用导出方法
        HSSFWorkbook wb = getHSSFWorkbook(sheetName, title, list, null);

        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success("导出成功");
    }

导出方法


    //导出切片excel的方法
    public HSSFWorkbook getHSSFWorkbook(String sheetName, List<String> title, List<EquipmentContrastDTO> list, HSSFWorkbook wb) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
        if (wb == null) {
            wb = new HSSFWorkbook();
        }

        // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(sheetName);

        // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        HSSFRow row = sheet.createRow(0);
        row.setHeight((short) 650);
        // 第四步,创建单元格,并设置表头值 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        //声明列对象
        HSSFCell cell = null;

        //创建标题
        for (int i = 0; i < title.size(); i++) {
            sheet.setColumnWidth(i, 6000);
            cell = row.createCell(i);
            cell.setCellValue(title.get(i));
            HSSFFont font = wb.createFont();
            font.setFontName("黑体");
            font.setFontHeightInPoints((short) 15);//设置字体大小
            style.setFont(font);
            cell.setCellStyle(style);
        }
        try {
            //创建内容
            HSSFCellStyle styleCon = wb.createCellStyle();
            styleCon.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
            styleCon.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
            for (int i = 0; i < list.size(); i++) {
                BufferedImage bufferImg = null;//图片一
                row = sheet.createRow(i + 1);
                row.setHeight((short) 550);
                EquipmentContrastDTO keeSpecimen = list.get(i);
                List<FdEquipmentParameterVo> parameterList = keeSpecimen.getFdEquipmentParameterList();//参数
                //图片路径
                String imagePath = list.get(i).getShowPicture();
                HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
                if (StrUtil.isNotEmpty(imagePath)) {
                    URL url = new URL(imagePath);
                    String formatName = imagePath.substring(imagePath.lastIndexOf(".") + 1);
                    bufferImg = ImageIO.read(url);
                    // 若省略下面一条语句,则出现问题(所有图片是第一次插入的图片)
                    byteArrayOut = new ByteArrayOutputStream();
                    ImageIO.write(bufferImg, formatName, byteArrayOut);
                    // 图片一导出到单元格A1中
                    HSSFClientAnchor anchor = new HSSFClientAnchor(480, 30, 700, 250,
                            (short) 1, i + 1, (short) 1, i + 1);
                    //插入图片
                    patriarch.createPicture(anchor, wb.addPicture(byteArrayOut
                            .toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
                }
                //按列添加数据,第一列为0,依次类推
                cell = row.createCell(0);
                cell.setCellValue(keeSpecimen.getEquipmentName());
                cell.setCellStyle(styleCon);
                int j = 1;
                for (int i1 = 0; i1 < parameterList.size(); i1++) {
                    j++;
                    cell = row.createCell(j);
                    cell.setCellValue(parameterList.get(i1).getParameterValue());
                    cell.setCellStyle(styleCon);
                }
            }
            return wb;
        } catch (Exception e) {
            // TODO: handle exception
            System.err.println(e.getMessage());
        }
        return wb;
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

导出示例

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值