当前位置:网站首页>EasyExcel comprehensive course combat
EasyExcel comprehensive course combat
2022-07-30 22:31:00 【Fairy wants to carry】
目录
Control layer uploadExcelFile reading course
场景
When we import course information,直接导入Excelfile to enter all course information,It is line mode to read file information,节省内存,效率较高;
Warm-up test
<dependencies>
<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.1</version>
</dependency>
</dependencies>
2.创建实体类
One is level one
package com.atguigu.demo.excel;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
@Data
public class DemoData {
//设置表头名称
@ExcelProperty(value = "学生编号",index = 0)
private Integer sno;
@ExcelProperty(value = "学生姓名",index = 1)
private String sname;
}
实现写操作,对Excel
指定文件名,在文件中write(),并且封装data数据
public static void main(String[] args) throws Exception {
// 写法1
String fileName = "F:\\11.xlsx";
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
// 如果这里想使用03 则 传入excelType参数即可
EasyExcel.write(fileName, DemoData.class).sheet("写入方法一").doWrite(data());
}
//循环设置要添加的数据,最终封装到list集合中
private static List<DemoData> data() {
List<DemoData> list = new ArrayList<DemoData>();
for (int i = 0; i < 10; i++) {
DemoData data = new DemoData();
data.setSno(i);
data.setSname("张三"+i);
list.add(data);
}
return list;
}
对Excel读数据
主要是通过ExcelListener监听器从Excelto get row data
package com.atguigu.demo.excel;
import com.alibaba.excel.EasyExcel;
import java.util.ArrayList;
import java.util.List;
public class TestEasyExcel {
public static void main(String[] args) {
String filename="D:\\write.xlsx";
// EasyExcel.write(filename,DemoData.class).sheet("学生列表").doWrite(getData());
/**
* 4.读取excel
* 读取filename,利用监听器,Output each line of content
*/
EasyExcel.read(filename,DemoData.class,new ExcelListener()).sheet().doRead();
}
/**
* 3.Returns with datalist
*/
private static List<DemoData> getData(){
ArrayList<DemoData> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
DemoData data = new DemoData();
data.setSno(i);
data.setSname("Lucy"+i);
list.add(data);
}
return list;
}
}
读取Excel文件的监听器,监听我们的fileName
package com.atguigu.demo.excel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
public class ExcelListener extends AnalysisEventListener<DemoData> {
/**
* 1.一行一行读取数据
* @param demoData
* @param analysisContext
*/
@Override
public void invoke(DemoData demoData, AnalysisContext analysisContext) {
System.out.println("****"+demoData);
}
/**
* 2.To read the information in the header
* @param
*/
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
System.out.println("表头:"+headMap);
}
/**
* 3.what to do after reading it
* @param analysisContext
*/
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
}
项目结合
一级分类
package com.atguigu.eduservice.entity.subject;
import lombok.Data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
//一级分类
@Data
public class OneSubject implements Serializable {
private String id;
private String title;
/**
* 一个一级分类里面有多个二级分类(用集合表示)
*/
private List<TwoSubject> children=new ArrayList<>();
}
二级分类
package com.atguigu.eduservice.entity.subject;
import lombok.Data;
import java.io.Serializable;
//二级分类
@Data
public class TwoSubject implements Serializable {
private String id;
private String title;
}
Control layer uploadExcelFile reading course
@RestController
@RequestMapping("/eduservice/subject")
@CrossOrigin
public class EduSubjectController {
@Autowired
private EduSubjectService subjectService;
/**
* 1.添加课程分类
* Get the file uploaded by the user and read it
* @Param: MultipartFile
*/
@PostMapping("addSubject")
public R addSubject(MultipartFile file){
//1.1上传过来的excel文件
subjectService.saveSubject(file,subjectService);
return R.ok();
}
}
The business layer readsExcel
注意:Here we need to pay attention to the incoming of our control layersubjectService,Then in the business layerExcelListenerThe listener is encapsulatedsubejectService,It should be noted that there is a case of mutual calls here,So can't give bothSpring管理,所以我们没有@AutoWired注入subjectService,Rather, it is in the form of passing parameters
Here is another popularization of the course information display process(树形):
1.首先Wrapperpackage parentid=0的所有数据,也就是一级分类,Then we query the parent againid!=1The classification is the secondary classification——>2.Then we encapsulate the first-level classification,Convert the first-level classification to our packageOneSubject——>3.Then our encapsulated first-class classification collection is traversed,Each primary category has a secondary category set attribute,Traverse the secondary classification collection,如果二级idA first-level parentid,The current secondary classification is added to the secondary classification set——>4.The last level of classification is added to this collection,Returns a collection of primary categories
package com.atguigu.eduservice.service.impl;
import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.R;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.entity.subject.OneSubject;
import com.atguigu.eduservice.entity.subject.TwoSubject;
import com.atguigu.eduservice.listener.SubjectExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* <p>
* 课程科目 服务实现类
* </p>
*
* @author testjava
* @since 2022-07-11
*/
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {
/**
* 1.添加课程分类,需要读取excel文件
*
* @param file 注意这里new的listener,我们传入serviceThe purpose is to automatically inject circular dependencies,listener调用service,service调用listener,So cannot use the same oneservice
*/
@Override
public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
try {
InputStream in = file.getInputStream();
EasyExcel.read(in, SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 2.获取课程信息
*
* @return
*/
@Override
public List<OneSubject> getAllOneTwoSubject() {
//1.查询所有的一级分类
QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
wrapper.eq("parent_id", "0");
List<EduSubject> oneSubjectList = this.list(wrapper);
//2.查询所有的二级分类
QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
wrapperTwo.ne("parent_id", "0");
List<EduSubject> twoSubjectList = this.list(wrapperTwo);
//3.封装所有的一级分类
/**
* 查询出来所有的一级分类listThe collection is traversed to get each first-level object,获取每个一级分类对象值
* 然后封装到List<OneSubject>中
*/
List<OneSubject> finalSubjectList = oneSubjectList.stream().map(eduSubject -> {
OneSubject oneSubject = new OneSubject();
BeanUtils.copyProperties(eduSubject, oneSubject);
return oneSubject;
}).collect(Collectors.toList());
//4.The primary category encapsulates all secondary categories
for (OneSubject oneSubject : finalSubjectList) {
ArrayList<TwoSubject> twoFinalSubjectList = new ArrayList<>();
for (EduSubject subject : twoSubjectList) {
if(subject.getParentId().equals(oneSubject.getId())){
TwoSubject twoSubject = new TwoSubject();
BeanUtils.copyProperties(subject,twoSubject);
twoFinalSubjectList.add(twoSubject);
}
}
oneSubject.setChildren(twoFinalSubjectList);
}
return finalSubjectList;
}
}
Excel的监听器
1.首先,There are two classification methods,Determine whether two categories exist,并且返回——>2.如果不为空就返回,Add if empty——>3.ExcelEasy是一行一行读取,传入SubjectData实体类,It encapsulates the primary classification and the secondary classification
package com.atguigu.eduservice.entity.excel;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
@Data
public class SubjectData {
//一级分类和二级分类
@ExcelProperty(index = 0)
private String oneSubjectName;
@ExcelProperty(index = 1)
private String twoSubjectName;
}
package com.atguigu.eduservice.listener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.exceptionHandler.GuliException;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
/**
* Read and store through listeners
*/
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
/**
* 1.SubjectExcelListener不能交给Spring管理,Otherwise it will cause circular dependencies
*/
public EduSubjectService subjectService;
//手动传subjectService
public SubjectExcelListener() {}
public SubjectExcelListener(EduSubjectService subjectService) {
this.subjectService = subjectService;
}
/**
* 2.监听获取excelrow-by-row data
* @param subjectData
* @param analysisContext
*/
@Override
public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
//2.1判断数据是否为空
if(subjectData==null){
throw new GuliException(20001,"文件数据为空");
}
//2.2一行行读取(一行一列:一级分类),每次读取两个值,一个一级分类,一个二级分类
EduSubject existOneSubject = this.existOneSubject(subjectService, subjectData.getOneSubjectName());
if(existOneSubject==null){
//没有相同的一级分类,We add a new primary category
existOneSubject = new EduSubject();
existOneSubject.setParentId("0");
existOneSubject.setTitle(subjectData.getOneSubjectName());
subjectService.save(existOneSubject);
}
//2.3获取一级分类id
String pid = existOneSubject.getId();
//2.4添加二级分类,It is necessary to judge whether the secondary classification is repeated
EduSubject existTwoSubject = this.existTwoSubject(subjectService, subjectData.getTwoSubjectName(), pid);
if(existTwoSubject==null){
existTwoSubject=new EduSubject();
existTwoSubject.setParentId(pid);
existTwoSubject.setTitle(subjectData.getTwoSubjectName());
subjectService.save(existTwoSubject);
}
}
/**
* 3.一级title的判断
* 这里用subjectServiceThe purpose may need to be called elsewhere
* @param
*/
private EduSubject existOneSubject(EduSubjectService subjectService,String name){
QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
wrapper.eq("title",name);
wrapper.eq("parent_id","0");
EduSubject oneSubject = subjectService.getOne(wrapper);
return oneSubject;
}
/**
* 3.Judgment of secondary classification,Get secondary labels
* @param subjectService
* @param name:课程名称
* @param pid:课程号
*/
private EduSubject existTwoSubject(EduSubjectService subjectService,String name,String pid){
QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
wrapper.eq("title",name);
wrapper.eq("parent_id",pid);
EduSubject oneSubject = subjectService.getOne(wrapper);
return oneSubject;
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
}
边栏推荐
猜你喜欢
OpenCV笔记(二十):滤波函数——filter2D
Gxlcms audio novel system/novel listening system source code
鳄梨价格数据集(Avocado Prices)
cookie和session区别
Solve the problem of centos8 MySQL password ERROR 1820 (HY000) You must reset your password using the ALTER USER
MySQL Soul 16 Questions, How Many Questions Can You Last?
MySQL压缩包方式安装,傻瓜式教学
MySQL进阶sql性能分析
IDEA 连接 数据库
c语言进阶篇:指针(五)
随机推荐
Navicat cannot connect to mysql super detailed processing method
打动中产精英群体,全新红旗H5用产品力跑赢需求
Solve the problem of centos8 MySQL password ERROR 1820 (HY000) You must reset your password using the ALTER USER
proxy反向代理
OpenCV笔记(二十):滤波函数——filter2D
成功解决ImportError: cannot import name ‘_validate_lengths‘
IDEA2021.2安装与配置(持续更新)
小心你的字典和样板代码
MYSQL JDBC图书管理系统
VS2017 compile Tars test project
Rust编译报错:error: linker `cc` not found
ClickHouse to create a database to create a table view dictionary SQL
Go语学习笔记 - gorm使用 - gorm处理错误 Web框架Gin(十)
【无标题】
2022.7.28
折叠旧版应用程序
MySQL compressed package installation, fool teaching
鳄梨价格数据集(Avocado Prices)
【微信小程序】小程序突破小程序二维码数量限制
navicat新建数据库