SpringBoot中使用EasyExcel并行导出多个excel文件并压缩zip后下载

❃博主首页 : 「码到三十五」 ,同名公众号 :「码到三十五」,wx号 : 「liwu0213」
☠博主专栏 : <mysql高手> <elasticsearch高手> <源码解读> <java核心> <面试攻关>
♝博主的话 : 搬的每块砖,皆为峰峦之基;公众号搜索「码到三十五」关注这个爱发技术干货的coder,一起筑基

背景

SpringBoot的同步导出方式中,服务器会阻塞直到Excel文件生成完毕,在处理大量数据的导出功能,利用CompletableFuture,我们可以将导出任务异步化,最后 这些文件进一步压缩成ZIP格式以方便下载:

DEMO代码:

@RestController
@RequestMapping("/export")
public class ExportController {

    @Autowired
    private ExcelExportService excelExportService;

    @GetMapping("/zip")
    public ResponseEntity<byte[]> exportToZip() throws Exception {
        List<List<Data>> dataSets = multipleDataSets();
        List<CompletableFuture<String>> futures = new ArrayList<>();
        // 异步导出所有Excel文件
         String outputDir = "path/to/output/dir/";
        for (List<Data> dataSet : dataSets) {
            futures.add(excelExportService.exportDataToExcel(dataSet, outputDir));
        }

        // 等待所有导出任务完成       
        CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).get(10, TimeUnit.MINUTES);;

        // 收集Excel文件路径
        List<String> excelFilePaths = futures.stream()
                .map(CompletableFuture::join) // 获取文件路径
                .collect(Collectors.toList());

        // 压缩文件
        File zipFile = new File("path/to/output.zip");
        try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile))) {
            for (String filePath : excelFilePaths) {
                zipFile(new File(filePath), zipOut, new File(filePath).getName());
            }
        }

        // 返回ZIP文件
        byte[] data = Files.readAllBytes(zipFile.toPath());
        return ResponseEntity.ok()
                .header("Content-Disposition", "attachment; filename=\"" + zipFile.getName() + "\"")
                .contentType(MediaType.parseMediaType("application/zip"))
                .body(data);
    }

    // 将文件添加到ZIP输出流中  
    private void zipFile(File file, ZipOutputStream zipOut, String entryName) throws IOException {  
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {  
            ZipEntry zipEntry = new ZipEntry(entryName);  
            zipOut.putNextEntry(zipEntry);  
            byte[] bytesIn = new byte[4096];  
            int read;  
            while ((read = bis.read(bytesIn)) != -1) {  
                zipOut.write(bytesIn, 0, read);  
            }  
            zipOut.closeEntry();  
        }  
    } 

    // 获取数据
    private List<List<Data>> multipleDataSets() {
    }
}

SpringBoot异步并行生成excel文件,利用EasyExcel库来简化Excel的生成过程:

@Service
public class ExcelExportService {

    private static final String TEMPLATE_PATH = "path/to/template.xlsx";

    @Autowired
    private TaskExecutor taskExecutor; 

    public CompletableFuture<Void> exportDataToExcel(List<Data> dataList, String outputDir) {
        Path temproaryFilePath = Files.createTempFile(outputDir, "excelFilePre",".xlsx");
        return CompletableFuture.runAsync(() -> {
            try (OutputStream outputStream = new FileOutputStream(temproaryFilePath )) {
                EasyExcel.write(outputStream, Data.class)
                        .withTemplate(TEMPLATE_PATH)
                        .sheet()
                        .doFill(dataList)
                        .finish();
               return temproaryFilePath.toString();
            } catch (IOException e) {
                throw new RuntimeException("Failed to export Excel file", e);
            }
        }, taskExecutor);
    }
}

关注公众号[码到三十五]获取更多技术干货 !

Spring Boot使用EasyExcel导出动态数据为Excel文件的代码如下: 1. 首先,我们需要导入`easyexcel`的依赖。在`pom.xml`文件添加以下依赖: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.3.0</version> </dependency> ``` 2. 创建一个Excel工具类,用于导出Excel文件。假设我们已经有一个名为`ExcelUtil`的工具类。 ```java import com.alibaba.excel.EasyExcel; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.util.List; @Component public class ExcelUtil { public void export(HttpServletResponse response, List<Object> data) throws IOException { // 设置响应头信息 response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf-8"); String fileName = URLEncoder.encode("导出文件", "UTF-8"); response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx"); // 导出Excel文件 EasyExcel.write(response.getOutputStream(), Object.class).sheet("Sheet1").doWrite(data); } public void exportTemplate(HttpServletResponse response) throws IOException { // 设置响应头信息 response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf-8"); String fileName = URLEncoder.encode("模板文件", "UTF-8"); response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx"); // 导出模板文件 InputStream inputStream = getClass().getClassLoader().getResourceAsStream("template.xlsx"); EasyExcel.write(response.getOutputStream()).withTemplate(inputStream).sheet().doWrite(null); } } ``` 3. 创建一个Controller类,用于处理导出Excel的请求。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/excel") public class ExcelController { @Autowired private ExcelUtil excelUtil; @GetMapping("/export") public void exportExcel(HttpServletResponse response) throws IOException { // 模拟动态数据,实际场景可以根据业务需求获取数据 List<Object> data = new ArrayList<>(); data.add("数据1"); data.add("数据2"); data.add("数据3"); // 导出Excel文件 excelUtil.export(response, data); } @GetMapping("/template") public void exportTemplate(HttpServletResponse response) throws IOException { // 导出Excel模板文件 excelUtil.exportTemplate(response); } } ``` 以上代码演示了使用Spring BootEasyExcel导出动态数据为Excel文件的过程。在Controller,我们可以根据实际业务需求获取数据,并调用`ExcelUtil`的方法实现导出操作。同时,我们也提供了导出Excel模板文件的方法,以方便用户进行数据录入。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码到三十五

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值