当前位置:网站首页>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) {
}
}

边栏推荐
- MySQL 用户授权
- When Navicat connects to MySQL, it pops up: 1045: Access denied for user 'root'@'localhost'
- 通过社交媒体建立个人IP的 5 种行之有效的策略
- MySQL联合查询(多表查询)
- CISP-PTE真题演示
- 鳄梨价格数据集(Avocado Prices)
- 成功解决ImportError: cannot import name ‘_validate_lengths‘
- mysql去除重复数据
- Navicat连接MySQL时弹出:1045:Access denied for user ‘root’@’localhost’
- 解决npm warn config global `--global`, `--local` are deprecated. use `--location=global` instead
猜你喜欢

ML's shap: Based on FIFA 2018 Statistics (2018 Russia World Cup) team match star classification prediction data set using RF random forest + calculating SHAP value single-sample force map/dependency c

cmd(命令行)操作或连接mysql数据库,以及创建数据库与表

只会纯硬件,让我有点慌

The most complete Redis basic + advanced project combat summary notes in history

c语言进阶篇:指针(五)

MySQL 5.7详细下载安装配置教程

ML之shap:基于FIFA 2018 Statistics(2018年俄罗斯世界杯足球赛)球队比赛之星分类预测数据集利用RF随机森林+计算SHAP值单样本力图/依赖关系贡献图可视化实现可解释性之攻略

通过社交媒体建立个人IP的 5 种行之有效的策略

matlab标量场作图

史上最全的Redis基础+进阶项目实战总结笔记
随机推荐
【Untitled】
ClickHouse删除数据之delete问题详解
d违反常了吗
成功解决ModuleNotFoundError: No module named ‘Image‘
代码越写越乱?那是因为你没用责任链
【高等数学】矩阵与向量组的秩和等价
Chapter 8 Intermediate Shell Tools II
连号区间数
Jetson AGX Orin 平台关于c240000 I2C总线和GMSL ses地址冲突问题
1064 Complete Binary Search Tree
MySQL联合查询(多表查询)
Gxlcms有声小说系统/小说听书系统源码
IDEA使用技巧
【CTF】buuctf web 详解(持续更新)
ML之shap:基于FIFA 2018 Statistics(2018年俄罗斯世界杯足球赛)球队比赛之星分类预测数据集利用RF随机森林+计算SHAP值单样本力图/依赖关系贡献图可视化实现可解释性之攻略
解决npm warn config global `--global`, `--local` are deprecated. use `--location=global` instead
ClickHouse 创建数据库建表视图字典 SQL
IDEA usage skills
MySQL 用户授权
MySQL索引常见面试题(2022版)