Excel優雅匯出

ingxx發表於2020-12-15

流程

原來寫過一篇文章,是介紹EasyExcel的,但是現在有些業務需要解決,流程如下
1.需要把匯出條件轉換成中文並存入資料庫
2.需要分頁匯出
3.需要上傳FTP或者以後上傳OSS

解決方案

大體的流程採用摸板方法模式,這樣簡化條件轉換以及上傳FTP操作

public abstract class EasyExcelUtil {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final CloudOrderManagementDao cloudOrderManagementDao;

    //上下文物件
    private final ExportDTO dto;

    //ftp資訊
    private final FileClient fileClient;

    protected final RedisUtil redisUtil;


    private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 30,
            60L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100));;
    /**
     * 構造方法子類必須實現
     *
     * @param cloudOrderManagementDao dao
     * @param dto                     上下文物件
     * @param fileClient              檔案上傳物件
     * @param redisUtil               redis
     */
    public EasyExcelUtil(CloudOrderManagementDao cloudOrderManagementDao, ExportDTO dto, FileClient fileClient, RedisUtil redisUtil) {
        this.cloudOrderManagementDao = cloudOrderManagementDao;
        this.dto = dto;
        this.fileClient = fileClient;
        this.redisUtil = redisUtil;
    }

    /**
     * 主方法
     */
    public final void createExcel() {
        try {
            File file = this.createFile();
            CloudExportInfo exportInfo = this.createExportInfo(file.getName());
            threadPoolExecutor.execute(() -> {
                this.easyCreate(file);
                this.uploadFile(file);
                updateExportInfo(exportInfo);
            });
        } catch (Exception e) {
            logger.error("ExcelUtil error{}", e);
        }
    }

    /**
     * 建立檔案
     *
     * @return 檔案物件
     * @throws IOException
     */
    private File createFile() throws IOException {
        File temp = File.createTempFile("temp", ".xlsx");
        logger.info("ExcelUtil建立檔案成功{}", temp.getAbsolutePath());
        return temp;
    }


    /**
     * 建立匯出物件,並存資料庫
     *
     * @param fileName 檔名
     * @return 匯出物件
     */
    private CloudExportInfo createExportInfo(String fileName) {
        CloudExportInfo exportInfo = new CloudExportInfo();
        exportInfo.setId(dto.getUuid());
        exportInfo.setUserId(dto.getUserId());
        exportInfo.setCreateBy(dto.getUserName());
        exportInfo.setExportStatus(com.blgroup.vision.common.utils.R.CloudConstant.TWO);
        exportInfo.setExportType(dto.getExportType());
        exportInfo.setQueryParam(this.transitionQuery());
        exportInfo.setExportCount(dto.getTotal());
        exportInfo.setFileName(fileName);
        exportInfo.setExportDir(dto.getBasisDir() + File.separator + fileName);
        cloudOrderManagementDao.saveExportInfo(exportInfo);// 初始化匯出資訊
        redisUtil.set(R.CloudConstant.CLOUD_DOWNLOAD_PROGRESS + "_" + dto.getUuid(), "5", 60 * 5);
        logger.info("ExcelUtil建立匯出資訊成功{}", JSON.toJSONString(exportInfo));
        return exportInfo;
    }

    /**
     * 上傳檔案
     *
     * @param file 檔案,策略模式 未來可能支援OSS
     */
    private void uploadFile(File file) {
        redisUtil.set(R.CloudConstant.CLOUD_DOWNLOAD_PROGRESS + "_" + dto.getUuid(), "95", 60 * 5);
        fileClient.uploadFile(file, dto.getBasisDir());
        redisUtil.set(R.CloudConstant.CLOUD_DOWNLOAD_PROGRESS + "_" + dto.getUuid(), "100", 60 * 5);
    }

    /**
     * 上傳完成,更新匯出物件
     *
     * @param exportInfo
     * @return
     */
    private CloudExportInfo updateExportInfo(CloudExportInfo exportInfo) {
        exportInfo.setExportStatus(com.blgroup.vision.common.utils.R.CloudConstant.ONE);
        cloudOrderManagementDao.saveExportInfo(exportInfo);// 初始化匯出資訊
        logger.info("ExcelUtil上完成");
        return exportInfo;
    }

    /**
     * 匯出方法,可以實現分批匯出,也可以一次性匯出
     *
     * @param file 檔案
     */
    public abstract void easyCreate(File file);

    /**
     * 對查詢欄位進行轉換
     * @return
     */
    public abstract String transitionQuery();
}

這樣子類只需要實現easyCreatetransitionQuery方法即可

查詢條件轉換

針對查詢條件轉換,例如QO欄位為'merchantId' 需要轉換為商戶值需要轉換為ID對應的商戶名稱
如果是每個匯出方法寫一段轉換類太麻煩這裡使用註解的方式
在屬性上使用表明中文意思和轉換方法

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface FieldNameTransition {
    /**
     * 中文名稱
     * @return
     */
    String value();


    String transitionMethod() default "";


}

指定轉換類

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
/**
 * 指定轉換類
 */
public @interface TransitionClass {
    Class<?> value();
}

通過反射進行轉換

public class ExcelTransitionFieldUtil {
    public static Logger logger = LoggerFactory.getLogger(ExcelTransitionFieldUtil.class);

    private final ApplicationContext applicationContext;

    public ExcelTransitionFieldUtil(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public String transition(Object object) {
        List<Map<String, String>> resultList = new ArrayList<>();
        Object transitionBean = null;
        //獲取傳過來的物件
        Class<?> dtoClass = object.getClass();
        if (dtoClass.isAnnotationPresent(TransitionClass.class)) {
            //獲取類上的註解,得到轉換類 獲取spring ioc中轉換類的物件
            transitionBean = applicationContext.getBean(dtoClass.getAnnotation(TransitionClass.class).value());
        }
        //獲取物件的全部欄位
        Field[] fields = dtoClass.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(FieldNameTransition.class)) {
                field.setAccessible(true);
                //獲取欄位中需要轉換的註解
                try {
                    if (field.get(object) != null && StringUtils.isNotBlank(field.get(object).toString())) {
                        FieldNameTransition fieldAnnotation = field.getAnnotation(FieldNameTransition.class);
                        Map<String, String> tempMap = new HashMap<>();
                        tempMap.put("name", fieldAnnotation.value());
                        //如果定義了轉換方法
                        if (StringUtils.isNotBlank(fieldAnnotation.transitionMethod()) && transitionBean != null) {
                            Method method = transitionBean.getClass().getMethod(fieldAnnotation.transitionMethod(), dtoClass);
                            Object invoke = method.invoke(transitionBean, object);
                            tempMap.put("value", invoke.toString());
                        } else {
                            tempMap.put("value", field.get(object).toString());
                        }
                        resultList.add(tempMap);
                    }
                }catch (Exception e){
                    logger.error("反射轉換髮生異常 {}", e);
                }
            }
        }
        return JSON.toJSONString(resultList);
    }
}

使用

QueryMerchantExportQO queryDTO = QueryMerchantExportQO.builder()
      .isNeedAudit(request.getParameter("isNeedAudit"))
      .keyword(request.getParameter("keyword"))
      .merchantType(request.getParameter("merchantType"))
      .shopId(request.getParameter("shopId"))
      .storeCode(request.getParameter("storeCode"))
      .storeType(request.getParameter("storeType"))
      .hideFlag(request.getParameter("hideFlag")).build();
ExportDTO exportDTO = ExportDTO.builder().userId(UserUtils.getUser().getId())
      .userName(UserUtils.getUser().getName())
      .exportType("9")
      .uuid(UUID.randomUUID().toString())
      .basisDir("/cloudDownFile" + File.separator + LocalDate.now().getYear() + File.separator + LocalDate.now().getMonth().getValue())
      .total(Integer.valueOf(request.getParameter("total")))
      .build();
FtpInfo ftpInfo = new FtpInfo(server, uname, pwd, port);
new EasyExcelUtil(cloudOrderManagementDao, exportDTO, new FtpFileClient(ftpInfo), redisUtil) {
      @Override
      public void easyCreate(File file) {
            //do something
      }

      @Override
      public String transitionQuery() {
			//轉換
      return new ExcelTransitionFieldUtil(applicationContext).transition(queryDTO);
      }
      }.createExcel();
}

結尾

現在問題是轉換型別只能是String型別,以後可能改進

相關文章