使用 easyexcel

使用easyexcel

1. pom引入依赖

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

2. Excel文件抽取及写入代码

   /**
     * 从 excel文件 抽取数据
     */
    public List<ExcelCouponDTO> getCheckDataFromExcel(String fileUrl) {
        List<ExcelCouponDTO> couponCheckDTOList = new LinkedList<>();
        Workbook workbook;
        try (InputStream is = getUrl(fileUrl).openStream()) {
            // 非excel文件则抛出异常
            if (!fileUrl.endsWith(ExcelTypeEnum.XLS.getValue())
                    && !fileUrl.endsWith(ExcelTypeEnum.XLSX.getValue())) {
                throw new ClientViewException("上传文件不是Excel类型文件,请检查");
            }
            if (fileUrl.endsWith(ExcelTypeEnum.XLS.getValue())) {
                workbook = new HSSFWorkbook(is);
            } else {
                workbook = new XSSFWorkbook(is);
            }
            int sheetCount = workbook.getNumberOfSheets();
            if (sheetCount == 0) {
                throw new com.bilibili.mall.common.exception.ClientViewException("文件为空!");
            }
            Sheet sheet = workbook.getSheetAt(0);
            int rowCount = sheet.getLastRowNum();
            if (rowCount < 1) {
                throw new com.bilibili.mall.common.exception.ClientViewException("文件内数据为空!");
            }
            // 从第一行读取
            for (int i = 1; i <= rowCount; i++) {
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                int cellCount = row.getFirstCellNum();
                if (cellCount < 0) {
                    continue;
                }
                ExcelCouponDTO couponCheckDTO = new ExcelCouponDTO();
                couponCheckDTO.setType(getCellFormatValue(row.getCell(0)));
                couponCheckDTOList.add(couponCheckDTO);
            }
        } catch (IOException e) {
            logger.error("读取 excel 文件内容错误", e);
        }
        return couponCheckDTOList;
    }
   public URL getUrl(String fileUrl) {
        URL url;
        try {
            fileUrl = fileUrl.startsWith("//") ? "http:" + fileUrl : fileUrl;
            url = new URL(fileUrl);
        } catch (Exception e) {
            throw new com.bilibili.mall.common.exception.ClientViewException(com.bilibili.mall.common.enums.ErrorCode.ILLEGAL_PARAM.getCode(), com.bilibili.mall.common.enums.ErrorCode.ILLEGAL_PARAM.getMessage());
        }
        return url;
    }
    public static String getCellFormatValue(Cell cell) {
        String cellValue;
        if (cell != null) {
            // 判断cell类型
            switch (cell.getCellTypeEnum()) {
                case NUMERIC:
                    double doubleVal = cell.getNumericCellValue();
                    long longVal = Math.round(cell.getNumericCellValue());
                    if (Double.parseDouble(longVal + ".0") == doubleVal) {
                        cellValue = String.valueOf(longVal);
                    } else {
                        cellValue = BigDecimal.valueOf(doubleVal).toPlainString();
                    }
                    break;
                case FORMULA:
                    // 判断cell是否为日期格式
                    if (DateUtil.isCellDateFormatted(cell)) {
                        // 转换为日期格式YYYY-mm-dd
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        cellValue = sdf.format(cell.getDateCellValue());
                    } else {
                        // 数字
                        cellValue = String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                case STRING:
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                default:
                    cellValue = "";
            }
        } else {
            cellValue = "";
        }
        return cellValue;
    }
    /**
     * 批量创券文件生成
     */
    @Async
    public String createMultiCouponFile(List<ExcelCouponDTO> couponCheckDTOList) {
        // 1. 构建文件名称
        String fileName = "批量优惠券信息-" + System.currentTimeMillis() + ".xlsx";
        String fileFullName = localFilePath + File.separator + fileName;
        // 2. 构建文件内容
        List<ExcelUtils.MultiCouponMode> bodyDataList = new ArrayList<>();
        for (ExcelCouponDTO couponCheckDTO : couponCheckDTOList) {
            ExcelUtils.MultiCouponMode multiCouponMode = new ExcelUtils.MultiCouponMode();
            BeanUtils.copyProperties(couponCheckDTO, multiCouponMode);
            if (Boolean.TRUE.equals(couponCheckDTO.getUploadStatus())) {
                multiCouponMode.setUploadStatus("上传成功");
            } else {
                multiCouponMode.setUploadStatus("上传失败");
            }
            if (couponCheckDTO.getCreateStatus() == null) {
                multiCouponMode.setCreateStatus("未创建");
            } else if (Boolean.TRUE.equals(couponCheckDTO.getCreateStatus())) {
                multiCouponMode.setCreateStatus("创建成功");
            } else {
                multiCouponMode.setCreateStatus("创建失败");
            }
            bodyDataList.add(multiCouponMode);
        }
        // 3. 创建文件
        try {
            ExcelUtils.createMultiCouponFile(fileFullName, bodyDataList);
        } catch (Exception e) {
            logger.error(" createMultiCouponFile 文件创建失败", e);
        }
        // 4. 上传文件
        File file = new File(fileFullName);
        try {
            amazonS3.putObject(bucket, fileName, file);
            // 5. 删除本地文件
            logger.info(" createMultiCouponFile 删除本地文件是否成功 {} {}", fileName, file.delete());
        } catch (SdkClientException e) {
            logger.error("createMultiCouponFile 上传文件失败", e);
        }
        return asyncSendAssetHandler.downloadUrl(fileName);
    }

      @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class MultiCouponMode {

        @ExcelProperty(value = "权益/资产类型", index = 0)
        private String type;

        @ExcelProperty(value = "优惠券名称", index = 1)
        private String couponName;
        }

    public static void createMultiCouponFile(String fileName, List<MultiCouponMode> multiCouponModes) throws Exception {
        createIfNecessary(fileName);
        ExcelWriter excelWriter = EasyExcelFactory.write()
                .head(MultiCouponMode.class)
                .file(fileName)
                .autoCloseStream(true)
                .build();
        excelWriter.write(multiCouponModes, EasyExcelFactory.writerSheet(1, "批量创券").build());
        excelWriter.finish();
    }

        private static void createIfNecessary(String fileName) throws Exception {
        File file = new File(fileName);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            if (!file.createNewFile()) {
                log.warn("create file failed");
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值