easyExcel
依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
</dependency>
@Data
public class SubjectEeVo {
@ExcelProperty(value = "id" ,index = 0)
private Long id;
@ExcelProperty(value = "课程分类名称" ,index = 1)
private String title;
@ExcelProperty(value = "上级id" ,index = 2)
private Long parentId;
@ExcelProperty(value = "排序" ,index = 3)
private Integer sort;
}
文件下载
(就是通过响应体携带文件 然后下载)
try {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("课程分类","utf8");
response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
List<Subject> dictList = baseMapper.selectList(null); //通过数据库获取
List<SubjectEeVo> dictVoList = new ArrayList<>(dictList.size());
for(Subject dict : dictList) {
SubjectEeVo dictVo = new SubjectEeVo();
BeanUtils.copyProperties(dict,dictVo);
dictVoList.add(dictVo);
}
EasyExcel.write(response.getOutputStream(), SubjectEeVo.class).sheet("课程分类").doWrite(dictVoList);
} catch (IOException e) {
e.printStackTrace();
}
文件导入
监听器
package com.atguigu.ggkt.vod.listener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.ggkt.model.vod.Subject;
import com.atguigu.ggkt.vo.vod.SubjectEeVo;
import com.atguigu.ggkt.vod.mapper.SubjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
@Component
public class ExcelListener extends AnalysisEventListener<SubjectEeVo> {
@Autowired
SubjectMapper subjectMapper;
//单行插入
@Override
public void invoke(SubjectEeVo subjectEeVo, AnalysisContext analysisContext) {
Subject subject = new Subject();
System.out.println(subjectEeVo);
BeanUtils.copyProperties(subjectEeVo,subject);
subjectMapper.insert(subject);
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
System.out.println("导入完成");
}
}
服务层
try {
EasyExcel.read(multipartFile.getInputStream(), SubjectEeVo.class, excelListener).sheet().doRead();
} catch (IOException e) {
e.printStackTrace();
}