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