Java实现多个sheet导入

controller层

public void import(@RequestParam("file") MultipartFile file){
if (Objects.isNull(file) || file.isEmpty()) {
            throw new WarnMessageException("导入文件为空");
        }
        // 文件名
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf(SymbolConst.SEPARATION_DOT));
        if (!"xlsx".equals(suffixName)) {
            throw new WarnMessageException("文件格式必须为.xlsx格式");
        }
        List<TrackPointInfoExcelDTO> trackPointInfoExcelDTOList;
        List<TrackDataTransInfoExcelDTO> transInfoExcelDTOList;
        List<TrackTriggerRuleExcelDTO> triggerRuleExcelDTOList;

        try {
            InputStream in = file.getInputStream();
            // 读取第一个sheet,从第二行开始读取 
            trackPointInfoExcelDTOList = ExcelExportAction.readImportExcel(in, TrackPointInfoExcelDTO.class, 0);
            //读取第二个sheet
            InputStream inputStream = file.getInputStream();
            transInfoExcelDTOList = ExcelExportAction.readImportExcel(inputStream, TrackDataTransInfoExcelDTO.class, 1);
            //读取第三个sheet
            InputStream fileInputStream = file.getInputStream();
            triggerRuleExcelDTOList = ExcelExportAction.readImportExcel(fileInputStream, TrackTriggerRuleExcelDTO.class, 2);
        } catch (Exception e) {
            throw new WarnMessageException("文件导入失败!,错误信息:" + e.getMessage());
        }

    //service层处理数据 可以自己写    
    trackPointRestService.importTrackInfo(trackPointInfoExcelDTOList, transInfoExcelDTOList,
                triggerRuleExcelDTOList, userId, userName);

}

处理读操作的方法

public static <T> List<T> readImportExcel(InputStream in, Class<T> objectClass, Integer sheetNo) {
//此处的监听器是我自己写的
        ExcelListener<T> excelListener = new ExcelListener<>();
        ExcelReaderBuilder readerBuilder = EasyExcel.read(in, objectClass, excelListener);
        ExcelReader reader = readerBuilder.build();
        ReadSheet readSheet = new ReadSheet(sheetNo);
        reader.read(readSheet);
        reader.finish();
        return excelListener.getRows();
    }

监听器的实现

public class ExcelListener<T> extends AnalysisEventListener<T> {

    private final List<T> rows = new ArrayList<>();

    @Override
    public void invoke(T model, AnalysisContext var2) {
        log.info("读取数据:{}", JsonHelper.toJson(model));
        if (!isBlankRowData(model)) {
            rows.add(model);
            return;
        }
        rows.add(model);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext var1) {
        log.info("read {} rows", rows.size());
    }

    public List<T> getRows() {
        return rows;
    }

    /**
     * 是否是空行
     *
     * @param model model
     * @return true 是空行、 false 不是空行
     */
    private boolean isBlankRowData(T model) {
        return StringUtils.isEmpty(JsonHelper.toJson(model));
    }
}

你可能感兴趣的:(java基础,java)