java-EasyExcel模板导出

发布时间 2023-11-24 10:40:14作者: Aa从心

前言: 

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

 

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

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

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

 

实际代码:

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")));
}

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);
    }

 

xlsx模板位置

xlsx模板内容

导出内容展示