easyexcel多sheet多线程导入示例,获取所以线程执行结果后返回

1.导入jar 

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

 2.excel sheet 对应实体

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;

@Data
public class ModelImportExcel {

    @ExcelProperty(value = "名称",index = 0)
    private String modelName;
    @ExcelProperty(value = "基础算法",index = 1)
    private String modelType;
   

}

3.实现代码

@Override
    public CommonResult exportAll(MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return CommonResult.failed("文件为空,请重新上传!");
        }
        StringBuffer buffer = new StringBuffer();
        try (InputStream input = file.getInputStream()) {
            List<ReadSheet> sheets = EasyExcel.read(input).build().excelExecutor().sheetList();
            // 存储每个 CompletableFuture 的结果
            List<CompletableFuture<String>> futures = new ArrayList<>();
            //在开启新线程前添加如下,让子线程共享主线程servletRequestAttributes
            ServletRequestAttributes servletRequestAttributes =
                    (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            RequestContextHolder.setRequestAttributes(servletRequestAttributes, true);
            for (ReadSheet ss : sheets) {
                String sheetName = ss.getSheetName().toLowerCase();
                try {
                    //起新线程,导入基础模型
                    CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                        log.info("当前线程:{}", Thread.currentThread().getName());
                        switch (sheetName) {
                            case "aaa":
                                exportModelaaa(file, ss, sheetName,buffer);
                                return "";
                            case "bbb":
                                exportModelbbb(file,ss,sheetName,buffer);
                                return "";
                            default: return "";
                        }
                    }, customExecutor);
                    futures.add(future);
                    continue;
                } catch (Exception e) {
                    Thread.currentThread().interrupt();
                    buffer.append(sheetName + " sheet,导入失败!");
                    e.printStackTrace();
                }
            }
            // 等待所有任务完成并获取结果
            for (CompletableFuture<String> future : futures) {
                try {
                    buffer.append(future.get()); // 阻塞直到任务完成并获取结果
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonResult.success(buffer);
    }
  

  

posted @ 2024-11-12 18:22  90的生力军  阅读(20)  评论(0编辑  收藏  举报