使用easypoi模板多线程导出excel文件并生成压缩文件下载,支持动态列

最近,面临了一个新的需求,需要将用户查询的数据导出到Excel文件中。为了满足这一需求,我决定采用EasyPoi库来实现该功能,并支持设置每个Excel文件的行数,并生成压缩包。下面,我将具体的实现方法分享给大家。

由于我使用的是SpringBoot框架,因此这里以SpringBoot为例进行讲解。对于其他框架,除了引入依赖的方式不同之外,并无其他区别。

一. 模板方式

1. 首先我们在pom文件引入easypoi的依赖,这里我们引入它的starter

<dependency>
      <groupId>cn.afterturn</groupId>
      <artifactId>easypoi-spring-boot-starter</artifactId>
      <version>4.3.0</version>
</dependency>

2. 创建一个excel.xls模板文件,这里我将它放置在项目中的resources目录下,模板格式如下


表格颜色,单元格样式什么的都可以自定义,主要在于数据处理上。上图中的{{}}中的内容都是可以接受传值,当然你也可以放在别的位置,比如你任务的末尾,excelTitle只是你要传入的字段名罢了,可以随便取,注意数据行一定要双括号{{}}包裹,userList就是你要传入的对象名,t就是对userList的简写。

代码实现如下,这里我们根据数据条数、每个excel文件的条数计算出需要生成多少个excel文件,然后每个文件提交一个线程。待所有线程执行完之后,做后续处理

1. controller层代码

    /**
     * 导出用户清单
     * @param response
     * @param exportSize 导出条数
     * @param partSize 单个文件条数
     */
    @PostMapping("exportUserInfoList")
    public void exportUserInfoList(HttpServletResponse response,
                                   HttpServletRequest request,
                                   @RequestParam("exportSize") int exportSize,
                                   @RequestParam("partSize") int partSize) throws Exception{
        userService.exportUserInfoList(exportSize,partSize,request,response);
    }

2. service层代码,对数据进行分片,这里我用的是hutool工具类中ListUtil.partition方法进行分片,当然你可以自行实现分片。我们创建一个ThreadPoolExecutor线程池用来提交线程,使用CountDownLatch程序计数器计数,传入线程数,这里也就是我们将要生成的文件个数,然后调用await()方法等待所有线程执行结束。最后关闭线程。

这里造数据我用的是Faker工具中的方法,大家可以自行修改
注意:params对象中的userList就对应上面模板中的userList,excelTitle即为标题,别的参数也可以在这里传,基于这个特点,也就可以实现动态表头,动态列名的需求

	private static final int CORE_POOL_SIZE = 10;

    private static final int MAX_POOL_SIZE = 20;

    /**
     * 临时文件存放路径
     */
    private static final String TEMP_FILE_PATH = "/home/workspace/tempFile/";

    /**
     * 导出用户清单
     *
     * @param exportSize 导出条数
     * @param partSize   单个文件条数
     */
    public void exportUserInfoList(int exportSize, int partSize, HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Map<String, Object>> userList = new ArrayList<>();
        Faker faker = new Faker(Locale.CHINA);
        for (int i = 1; i <= exportSize; i++) {
            Map<String, Object> userInfo = new HashMap<String, Object>() {{
                put("userId", faker.code().asin());
                put("userName", faker.name().username());
                put("age", 18);
                put("addr", faker.address().fullAddress());
                put("tel", faker.phoneNumber().cellPhone());
            }};
            userList.add(userInfo);
        }
        // 数据分片
        List<List<Map<String, Object>>> partition = ListUtil.partition(userList, partSize);
        // 模板地址
        String templateUrl = "excelTemplate/UserList.xls";
        String tempFolder = TEMP_FILE_PATH + IdUtil.simpleUUID();
        if (!FileUtil.exist(tempFolder)) {
            FileUtil.mkdir(tempFolder);
        }
        int taskSize = partition.size();
        CountDownLatch doneSignal = new CountDownLatch(taskSize);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, 60000, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(10));
        for (int i = 0; i < taskSize; i++) {
            int curPage = i + 1;
            int finalI = i;
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    String excelName = tempFolder + File.separator + "用户清单-" + curPage + ".xls";
                    try (OutputStream outputStream = new FileOutputStream(excelName)) {
                        File file = new File(excelName);
                        if (!file.exists()) {
                            file.createNewFile();
                        }
                        Map<String, Object> params = new HashMap<>();
                        // 获取每片的数据
                        params.put("userList", partition.get(finalI));
                        params.put("excelTitle", "用户清单");
                        TemplateExportParams templateExportParams = new TemplateExportParams(templateUrl);
                        Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams, params);
                        workbook.write(outputStream);
                        outputStream.flush();
                    } catch (IOException e) {
                        log.error(e.getMessage());
                        e.printStackTrace();
                    } finally {
                        doneSignal.countDown();
                    }
                }
            });
            executor.execute(thread);
            System.out.println("提交线程---" + i);
        }
        doneSignal.await();
        executor.shutdown();
        InputStream ins = null;

        try {
            String zipFilePath = tempFolder + File.separator + "用户清单.zip";
            zipFolder(tempFolder, zipFilePath);
            handleResponseHeader("用户清单.zip", request, response);
            ins = new FileInputStream(zipFilePath);
            IOUtils.copy(ins, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(ins);
        }

    }

3. 下面是我用来生成压缩文件的方法,我封装成了工具类,大家可以直接拿去用

/**
     * 压缩文件
     * @param sourceFolderPath 要压缩的文件夹 例:D:temp/user
     * @param zipFilePath 压缩包路径 D:temp/user1.zip
     */
    public static void zipFolder(String sourceFolderPath, String zipFilePath) {
        try {
            FileOutputStream fos = new FileOutputStream(zipFilePath);
            ZipOutputStream zos = new ZipOutputStream(fos);
            zipDirectory(sourceFolderPath, sourceFolderPath, zos);
            zos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
   public static void zipDirectory(String rootPath, String sourceFolderPath, ZipOutputStream zos) throws IOException {

        // 创建一个File对象。
        File folder = new File(sourceFolderPath);

        // 列出文件夹中的所有文件和子文件夹。
        for (String fileName : folder.list()) {

            // 如果文件名以.zip结尾,即这是一个已经压缩的文件,
            // 那么就跳过这个文件,不将其压缩。
            if (fileName.endsWith(".zip")) {
                continue;
            }

            // 创建文件的完整路径。
            String filePath = sourceFolderPath + File.separator + fileName;

            // 如果该路径对应的文件是一个目录,那么递归调用此方法,
            // 继续压缩这个目录下的文件。
            if (new File(filePath).isDirectory()) {
                zipDirectory(rootPath, filePath, zos);
                continue;
            }

            String relativePath = filePath.substring(rootPath.length() + 1);
            ZipEntry ze = new ZipEntry(relativePath);

            // 将这个ZipEntry对象添加到ZipOutputStream中,这实际上是在zip文件中添加一个新的条目。
            zos.putNextEntry(ze);

            // 创建一个FileInputStream对象来读取文件。
            FileInputStream fis = new FileInputStream(filePath);
            byte[] buffer = new byte[1024];

            // 定义一个变量用于存储从文件中读取的字节的数量。
            int len;

            // 循环读取文件的数据,并将数据写入到zip文件中。
            while ((len = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            fis.close();
            // 关闭ZipEntry,这实际上是表示zip文件中的一个条目的结束。
            zos.closeEntry();
        }
    }

4. 下面是一个处理下载响应的方法。笔者发现有时在火狐浏览器中下载出的文件名乱码,所以针对火狐浏览器做了优化

/**
     * 设置响应头
     *
     * @param fileName 文件名
     * @param request
     * @param response
     */
    public static void handleResponseHeader(String fileName, HttpServletRequest request, HttpServletResponse response) {
        // 文件名
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        String header = request.getHeader("User-Agent");
        try {
            if (header.contains("Firefox")) {
                //解决火狐浏览器下载时文件名乱码的问题
                response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));
            } else {
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            }
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
            e.printStackTrace();
        }
    }

二. 注解方式

1. 首先准备一个实体类,加上Excel注解,name即为你的列名,orderNum即为列的顺序,width为列的宽度。

在这里插入图片描述

@Data
@AllArgsConstructor
@NoArgsConstructor
@ExcelTarget("tableListExcel")
public class TableExcel implements Serializable {
 
    /**
     * 名称
     */
    @Excel(name = "名称",orderNum = "1",width = 4)
    private String name;

    /**
     * 类型
     */
    @Excel(name = "年龄",orderNum = "2",width = 3)
    private String age;
 
    /**
     * 可为空
     */
    @Excel(name = "住址",orderNum = "3",width = 2)
    private String addr;

    /**
     * 注释
     */
    @Excel(name = "电话号码",orderNum = "4",width = 5)
    private String tel;
    
}

controller层

    @GetMapping("exportSysTableInfo")
    public void exportSysTableInfo(HttpServletRequest request,HttpServletResponse response ) {
        sysConfigService.exportExcel(response);
    }

service层

public void exportExcel(HttpServletResponse response) {
        // 这里是sheete的集合
        List<Map<String, Object>> sheetsList = new ArrayList<>();
        List<TableExcel> excels1 = new ArrayList<>();
        List<TableExcel> excels2 = new ArrayList<>();
        List<TableExcel> excels3 = new ArrayList<>();
        // 构建你的测试数据
        TableExcel tableExcel1 = new TableExcel("张三", "23", "上海市奉贤区", "15888888888");
        excels1.add(tableExcel1);
        TableExcel tableExcel2 = new TableExcel("李四", "32", "上海市普陀区", "0394-451212");
        excels2.add(tableExcel2);
        TableExcel tableExcel3 = new TableExcel("王五", "47", "上海市静安区", "65123222222");
        excels3.add(tableExcel3);

        // 创建参数对象
        ExportParams exportParams = new ExportParams();
        // 设置sheet的名称
        exportParams.setSheetName("001");
        // 创建sheet使用的map
        Map<String, Object> tableDataMap = new HashMap<>(4);
        tableDataMap.put("title", exportParams);
        tableDataMap.put("entity", TableExcel.class);
        tableDataMap.put("data", excels1);
        sheetsList.add(tableDataMap);

        // 创建参数对象
        ExportParams exportParams2 = new ExportParams();
        // 设置sheet2的名称
        exportParams2.setSheetName("002");
        // 创建sheet2使用的map
        Map<String, Object> tableDataMap2 = new HashMap<>(4);
        tableDataMap2.put("title", exportParams2);
        tableDataMap2.put("entity", TableExcel.class);
        tableDataMap2.put("data", excels2);
        sheetsList.add(tableDataMap2);

        // 创建参数对象
        ExportParams exportParams3 = new ExportParams();
        // 设置sheet3的名称
        exportParams3.setSheetName("003");
        // 创建sheet3使用的map
        Map<String, Object> tableDataMap3 = new HashMap<>(4);
        tableDataMap3.put("title", exportParams3);
        tableDataMap3.put("entity", TableExcel.class);
        tableDataMap3.put("data", excels3);
        sheetsList.add(tableDataMap3);

        Workbook workbook = ExcelExportUtil.exportExcel(sheetsList, ExcelType.HSSF);
        ExcelUtil.downLoadExcel("easyPOI导出表测试", response, workbook);
    }
生成Excel效果如下:001,002,003即为自定义的多个sheet页
在这里插入图片描述
在这里插入图片描述

ExcelUtil 工具类


	/**
     * Excel 类型枚举
     */
    enum ExcelTypeEnum {

        XLS("xls"), XLSX("xlsx");

        private String value;

        ExcelTypeEnum(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
    
	/**
     * 下载文件
     * @param fileName 文件名称
     * @param response
     * @param workbook excel数据
     */
    public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook){
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLS.getValue(), "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

好了,以上就是如何使用EasyPoi库和多线程技术来高效地导出Excel文件的方案。我希望这篇博客能对你有所帮助,也欢迎你提出任何建议和问题,让我们一起进步!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值