java Excel文件上传 解析入库

    @ApiOperation("上传文件")
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public BusinessResult uploadFile(@RequestParam("file") MultipartFile file) {
        return productCommentService.uploadFile(file);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BusinessResult uploadFile(MultipartFile file) {
        if (file.isEmpty()) throw new BusinessException("上传失败,请选择文件");
        LoginUserVO user = getSysUser();
        if (null == user) return BusinessResult.fail("无法获取用户信息");
        String userId = user.getId();
        String userName = user.getName();
        Date date = new Date();
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (!fileType.equals(FILE_SUFFIXS[0]) && !fileType.equals(FILE_SUFFIXS[1])) {
            throw new BusinessException("只允许上传xlsx或xls文件");
        }
        try {
            ExcelListen excelListen = new ExcelListen();
            EasyExcel.read(file.getInputStream(), ProductReview.class, excelListen).doReadAll();
            List<ProductReview> data = excelListen.getData();
            if (CollectionUtils.isEmpty(data)) return BusinessResult.fail("文件数据为空");
            data.stream().forEach(item -> {
                item.setCreateTime(date);
                item.setCreator(userName);
                item.setCreatorId(userId);
            });
            Set<String> commentIds = data.stream().filter(item -> StringUtils.isNotBlank(item.getCommentId())).map(ProductReview::getCommentId).collect(Collectors.toSet());
            if (CollectionUtils.isEmpty(commentIds)) return BusinessResult.fail("评论id为空");
            List<String> list = new ArrayList<>();
            list.addAll(commentIds);
            productReviewDao.deleteBatch(list);
            List<List<ProductReview>> lists = Lists.partition(data, 500);
            lists.forEach(productReviews -> {
                productReviewDao.batchAdd(productReviews);
            });
        } catch (Exception e) {
            logger.error("Excel文件解析失败,异常:" + e.getMessage(), e);
            throw new BusinessException("Excel文件解析失败,异常:" + e.getMessage(), e);
        }
        return BusinessResult.success();
    }

util类

public class ExcelListen extends AnalysisEventListener<ProductReview> {

    private List<ProductReview> list = new ArrayList<>();

    @Override
    public void invoke(ProductReview data, AnalysisContext context) {
        list.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    public List<ProductReview> getData() {
        return list;
    }
}

实体类


@Data
public class ProductReview implements Serializable {
    private Long id;
    @ExcelProperty(value = "产品ID")
    private String productId;
    @ExcelProperty(value = "评论ID")
    private String commentId;
    @ExcelProperty(value = "尺码")
    private String size;
    @ExcelProperty(value = "颜色")
    private String color;
    @ExcelProperty(value = "评论内容")
    private String commentContent;
    @ExcelProperty(value = "评论时间")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date commentTime;
    @ExcelProperty(value = "附图")
    private String imageUrls;
    private String creatorId;
    private String creator;
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date createTime;
}

maven依赖

        <dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>5.0.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>5.0.0</version>
		</dependency>

文件常量名

private static final String[] FILE_SUFFIXS = {".xls", ".xlsx"};

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值