EasyExcel
步驟
1.導入maven坐標
<!--xls-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!--xlsx-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<!--easyexcel-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.1</version>
</dependency>
2.創建實體類,加入表頭注解(對應excel的數據)
package com.gyb.eduservice.entity.excel;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* @Author: 郜宇博
* @Date: 2021/10/2 16:57
*/
@Data
public class SubjectData {
/**
* 一級分類
* 注解代表在excel的第一列
*/
@ExcelProperty(index = 0)
private String oneSubjectName;
/**
* 二級分類
*/
@ExcelProperty(index = 1)
private String twoSubjectName;
}
3.創建要添加到數據庫的實體類
package com.gyb.eduservice.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* 課程科目
* </p>
*
* @author 郜宇博
* @since 2021-10-02
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="EduSubject對象", description="課程科目")
public class EduSubject implements Serializable {
private static final long serialVersionUID=1L;
@ApiModelProperty(value = "課程類別ID")
@TableId(value = "id", type = IdType.ID_WORKER_STR)
private String id;
@ApiModelProperty(value = "類別名稱")
private String title;
@ApiModelProperty(value = "父ID")
private String parentId;
@ApiModelProperty(value = "排序字段")
private Integer sort;
@ApiModelProperty(value = "創建時間")
@TableField(fill = FieldFill.INSERT)
private Date gmtCreate;
@ApiModelProperty(value = "更新時間")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date gmtModified;
}
4.創建一個監聽器,繼承AnalysisEventListener
package com.gyb.eduservice.listener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gyb.eduservice.entity.EduSubject;
import com.gyb.eduservice.entity.excel.SubjectData;
import com.gyb.eduservice.service.EduSubjectService;
import com.gyb.servicebase.exceptionhandler.MyException;
/**
* @Author: 郜宇博
* @Date: 2021/10/2 17:03
*/
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
/**
* 因為SubjectExcelListener,不能交給Spring容器管理,
* 所以不能使用@Autowire自動導入eduSubjectService,
* 因此需要使用構造函數獲取到eduSubjectService
*/
public EduSubjectService eduSubjectService;
public SubjectExcelListener(EduSubjectService eduSubjectService) {
this.eduSubjectService = eduSubjectService;
}
public SubjectExcelListener() {
}
/**
* 判斷一級分類是否重復
* @param oneName 一級分類的名稱
* @return
*/
private EduSubject judgeExistOneSubject(String oneName){
//獲取該名稱的一級分類,一級分類的parent_id為0
EduSubject oneSubject = eduSubjectService.getOne(
new QueryWrapper<EduSubject>()
.eq("title", oneName)
.eq("parent_id", "0"));
return oneSubject;
}
/**
* 判斷二級分類是否重復
* @param twoName 一級分類的名稱
* @return
*/
private EduSubject judgeExistTwoSubject(String twoName,String pid){
//獲取該名稱的一級分類,一級分類的parent_id為0
EduSubject twoSubject = eduSubjectService.getOne(
new QueryWrapper<EduSubject>()
.eq("title", twoName)
.eq("parent_id", pid));
return twoSubject;
}
/**
* 讀取方法
* 一行一行讀,沒有一級或二級分類就創建
* @param subjectData 傳入的文件數據
* @param analysisContext
*/
@Override
public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
if (subjectData == null){
throw new MyException(20001,"文件數據為空");
}
//一行一行讀,每行有兩個值,第一個是一級分類,第二個是二級分類
EduSubject one = this.judgeExistOneSubject(subjectData.getOneSubjectName());
//一級分類
//不重復。添加
if (one == null){
//創建對象
one = new EduSubject();
one.setParentId("0");
one.setTitle(subjectData.getOneSubjectName());
//添加到數據庫
eduSubjectService.save(one);
}
//獲取該二級分類對應一級分類的id值
String pid = one.getId();
//二級分類
EduSubject two = this.judgeExistTwoSubject(subjectData.getTwoSubjectName(), pid);
if (two == null){
//創建對象
two = new EduSubject();
two.setParentId(pid);
two.setTitle(subjectData.getTwoSubjectName());
//添加到數據庫
eduSubjectService.save(two);
}
}
/**
* 讀取之后表頭操作
* @param analysisContext
*/
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
}
5.在servie層編寫添加文件的方法
package com.gyb.eduservice.service.impl;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gyb.eduservice.entity.EduSubject;
import com.gyb.eduservice.entity.excel.SubjectData;
import com.gyb.eduservice.listener.SubjectExcelListener;
import com.gyb.eduservice.mapper.EduSubjectMapper;
import com.gyb.eduservice.service.EduSubjectService;
import com.gyb.servicebase.exceptionhandler.MyException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
/**
* <p>
* 課程科目 服務實現類
* </p>
*
* @author 郜宇博
* @since 2021-10-02
*/
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {
/**
* 添加課程分類
* @param file
*/
@Override
public void addSubject(MultipartFile file,EduSubjectService eduSubjectService) {
try {
InputStream inputStream = file.getInputStream();
//讀取文件內的內容,因為是一行行讀,因此第三個參數需要傳遞一個監聽器
EasyExcel.read(inputStream, SubjectData.class,new SubjectExcelListener(eduSubjectService))
.sheet()
.doRead();
} catch (IOException e) {
throw new MyException(20001,e.getMessage());
}
}
}
6.在controller層調用
package com.gyb.eduservice.controller;
import com.gyb.commonutils.Result;
import com.gyb.eduservice.service.EduSubjectService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
/**
* <p>
* 課程科目 前端控制器
* </p>
*
* @author 郜宇博
* @since 2021-10-02
*/
@RestController
@RequestMapping("/eduservice/edu-subject")
@CrossOrigin
public class EduSubjectController {
@Autowired
private EduSubjectService eduSubjectService;
/**
* 添加課程分類
* @param file 上傳的excel文件
* @return
*/
@PostMapping("addSubject")
@ApiOperation("添加文件")
public Result addSubject(MultipartFile file){
try {
eduSubjectService.addSubject(file,eduSubjectService);
} catch (Exception e) {
return Result.error().message(e.getMessage());
}
return Result.ok();
}
}