【Java】- EasyExcel模板导出

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

根据自定义模板导出Excel,包含图片、表格,采用EasyExcel


提示:以下是本篇文章正文内容,下面案例可供参考

一、导入Maven包

提示:EasyExcel请使用 3.0 以上版本

对图片操作最重要的类就是 WriteCellData 如果你的easyexcel没有这个类,说明你的版本太低,请升级到3.0以上

<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>easyexcel</artifactId>
     <version>3.2.1</version>
 </dependency>

二、代码实现

1.Controller

@ApiOperation("excel导出详情")
@PostMapping("excelExport")
public void excelExport(HttpServletResponse response,
                        @ApiParam("id {\"id\":\"xxx\"}") @RequestBody Map<String, String> data) {
    ExcelUitl.templateExport(response, researcherInformationService
                             .getDetail(data.get("id")));
}

2.ServiceImpl

public static String templateExport(HttpServletResponse response,ResearchDetailVo researchDetailVo) {
        InputStream is = null;
        try {
            // 取出模板
            is = ResourceUtil.getStream("classpath:templates/survey.xlsx");
            Map<String, Object> map = new HashMap<>(10);
            map.put("goOutDate", researchDetailVo.getGoOutDate());
            map.put("userName", researchDetailVo.getUserName());
            map.put("visitPlace", researchDetailVo.getVisitPlace());
            map.put("marketTrends", researchDetailVo.getMarketTrends());
            map.put("marketEnvironment", researchDetailVo.getMarketEnvironment());
            map.put("partnerTrends", researchDetailVo.getPartnerTrends());
            map.put("companyStatus", researchDetailVo.getCompanyStatus());
            map.put("marketCompetition", researchDetailVo.getMarketCompetition());
            map.put("feedback", researchDetailVo.getFeedback());

            // 文件名称
            String fileName = researchDetailVo.getUserName() + researchDetailVo.getGoOutDate()
                    + "调研反馈信息表";
   
            if (!ObjectUtils.isEmpty(researchDetailVo.getUrl())) {
                //图片url转换为MultipartFile对象
                // getUrl 是 List<String>
                MultipartFile[] files = downloadImages(researchDetailVo.getUrl());
                for (int i = 0; i < files.length; i++) {
                    MultipartFile file = files[i];
                    // 图像设置处理
                    WriteCellData<Void> voidWriteCellData = imageCells(file.getBytes());
                    map.put("img" + (i + 1), voidWriteCellData);
                }
            }

            ExcelWriter excelWriter = EasyExcel.write(getOutputStream(fileName, response)).withTemplate(is).excelType(ExcelTypeEnum.XLSX).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(map, writeSheet);
            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


public static WriteCellData<Void> imageCells(byte[] bytes) throws IOException {

        WriteCellData<Void> writeCellData = new WriteCellData<>();

        // 可以放入多个图片
        List<ImageData> imageDataList = new ArrayList<>();
        writeCellData.setImageDataList(imageDataList);

        ImageData imageData = new ImageData();
        imageDataList.add(imageData);
        // 设置图片
        imageData.setImage(bytes);
        // 图片类型
        //imageData.setImageType(ImageData.ImageType.PICTURE_TYPE_PNG);

        // 上 右 下 左 需要留空,这个类似于 css 的 margin;
        // 这里实测 不能设置太大 超过单元格原始大小后 打开会提示修复。暂时未找到很好的解法。
        imageData.setTop(10);
        imageData.setRight(10);
        imageData.setBottom(10);
        imageData.setLeft(10);

        // * 设置图片的位置。Relative表示相对于当前的单元格index。first是左上点,last是对角线的右下点,这样确定一个图片的位置和大小。
        // 目前填充模板的图片变量是images,index:row=CELL_COUNT,column=0。所有图片都基于此位置来设置相对位置
        // 第1张图片相对位置
        imageData.setRelativeFirstRowIndex(0);
        imageData.setRelativeFirstColumnIndex(0);
        imageData.setRelativeLastRowIndex(0);
        imageData.setRelativeLastColumnIndex(0);

        return writeCellData;
    }

///为什么用线程池去实现 原因:当时项目文件储存用的是minio,由于服务器宽带非常低,导致几百K的图片都需要很久,多图片需要加载资源很久
public static MultipartFile[] downloadImages(List<String> imageUrls) {
        // 创建一个固定大小的线程池
        int poolSize = 5;
        ThreadPoolExecutor executor = new ThreadPoolExecutor(poolSize, poolSize,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        MultipartFile[] files = new MultipartFile[imageUrls.size()];

        for (int i = 0; i < imageUrls.size(); i++) {
            final int index = i;
            executor.submit(() -> {
                try {
                    files[index] = convert(imageUrls.get(index));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }

        executor.shutdown(); // 关闭线程池

        // 等待所有任务执行完成
        while (!executor.isTerminated()) {
            // 等待
        }

        return files;
    }

    /**
     * 图片地址转换为MultipartFile文件
     *
     * @param imageUrl
     * @return
     * @throws IOException
     */
    public static MultipartFile convert(String imageUrl) throws IOException {
        // 将在线图片地址转换为URL对象
        URL url = new URL(imageUrl);
        // 打开URL连接 转换为HttpURLConnection对象
        URLConnection connection = url.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
        // 获取输入流 并读取输入流中的数据,并保存到字节数组中
        InputStream inputStream = httpURLConnection.getInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, bytesRead);
        }
        byte[] bytes = byteArrayOutputStream.toByteArray();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        return new MockMultipartFile("file", "filename.jpg", "image/jpeg", byteArrayInputStream);
    }

3.文件位置和模板

在这里插入图片描述
在这里插入图片描述

4.导出内容展示

在这里插入图片描述


  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值