SpringBoot整合EasyExcel(完整版包含上传解析excel和下载模板)1. 加⼊依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.7</version>
</dependency>
2. 对读取excel内容(批量添加)
@PostMapping("plUpdate")
public R plUpdate(@RequestParam("filename") MultipartFile file) throws IOException {
//String Originalfilename = OriginalFilename();
// String fileName = Name();
/
/ System.out.println("orname="+Originalfilename+";"+"filename"+Name());
// 获取⽂件全名
String fileName = OriginalFilename();
//设置⽂件路径
String templatePath = "G:/excel/";
File dest0 = new File(templatePath);
File dest = new File(dest0, fileName);
//⽂件上传-覆盖
try {
// 检测是否存在⽬录
if (!ParentFile().exists()) {
//检测⽂件是否存在
}
if (!ists()) {
dest.mkdirs();
}
} catch (Exception e) {
();
}
String finameUrl = templatePath+fileName;
ExcelReader excelReader = null;
try {
//TeacherExcel.class对应的是和模板⼀样的实体类,
//eduTeacherService对应持久层的接⼝
excelReader = ad(finameUrl, TeacherExcel.class, new DemoDataListener(eduTeacherService)).build();
ReadSheet readSheet = adSheet(0).build();
} finally {
if (excelReader != null) {
// 这⾥千万别忘记关闭,读的时候会创建临时⽂件,到时磁盘会崩的
excelReader.finish();
}
}
return R.ok();
}
创建⼀个监听类:
package l;
import l.context.AnalysisContext;
import l.event.AnalysisEventListener;
import com.ity.EduTeacher;
import com.ity.vo.TeacherExcel;
import com.atguigu.eduservice.service.EduTeacherService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
// 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后⾥⾯⽤到spring可以构造⽅法传进去
public class DemoDataListener extends AnalysisEventListener<TeacherExcel> {
private static final Logger LOGGER = Logger(DemoDataListener.class);
//这⾥写持久层的类
private EduTeacherService eduTeacherService;
/**
* 如果使⽤了spring,请使⽤这个构造⽅法。每次创建Listener的时候需要把spring管理的类传进来
*
* @param eduTeacherService
*/
public DemoDataListener( EduTeacherService eduTeacherService) {
//进⾏持久层的类
this.eduTeacherService = eduTeacherService;
}
/**
* 每隔5条存储数据库,实际使⽤中可以3000条,然后清理list ,⽅便内存回收
*/
private static final int BATCH_COUNT = 5;
List<TeacherExcel> list = new ArrayList<TeacherExcel>();
/**
* 假设这个是⼀个DAO,当然有业务逻辑这个也可以是⼀个service。当然如果不⽤存储这个对象没⽤。 */
//private DemoDAO demoDAO;
public DemoDataListener() {
// 这⾥是demo,所以随便new⼀个。实际使⽤如果到了spring,请使⽤下⾯的有参构造函数
//demoDAO = new DemoDAO();
}
/**
* 如果使⽤了spring,请使⽤这个构造⽅法。每次创建Listener的时候需要把spring管理的类传进来
*
* @param demoDAO
*/
getsavefilename/* public DemoDataListener(DemoDAO demoDAO) {
this.demoDAO = demoDAO;
}*/
/**
* 这个每⼀条数据解析都会来调⽤
*
* @param data
* one row value. Is is same as {@link AnalysisContext#readRowHolder()}
* @param context
*/
@Override
public void invoke(TeacherExcel data, AnalysisContext context) {
LOGGER.info("解析到⼀条数据:{}",String());
list.add(data);
// 达到BATCH_COUNT了,需要去存储⼀次数据库,防⽌数据⼏万条数据在内存,容易OOM
}
/**
* 所有数据解析完成了都会来调⽤
*
* @param context
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// 这⾥也要保存数据,确保最后遗留的数据也存储到数据库
saveData();
LOGGER.info("所有数据解析完成!");
}
/**
* 加上存储数据库
*/
private void saveData() {
LOGGER.info("{}条数据,开始存储数据库!", list.size());
//因为我excel模板的实体和插⼊数据库实体的类不⼀样,所以需要进⾏转化
for (int i =0;i<list.size();i++ ){
EduTeacher teacher = new EduTeacher();
teacher.(i).getLevel());
teacher.(i).getCareer());
teacher.(i).getName());
teacher.(i).getSort());
teacher.(i).getIntro());
boolean save = eduTeacherService.save(teacher);
if (save){
System.out.println("第"+i+"添加成功");
}
}
}
}
例如我的excel模板是:
实体类:
字段上ExcelProperty的注解可以使⽤index声明字段在模板中的顺序,使⽤value声明模板各个字段的名称。例如:
@ExcelProperty(value = “讲师简介”,index = 1)
private String intro;
模板的实体类要和excel字段⼀样对应,不然会出错
效果:
3. 模板下载:
创建⼀个⼯具类:
package com.fig;
import l.EasyExcel;
import l.support.ExcelTypeEnum;
import adata.style.WriteCellStyle;
import l.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.URLEncoder;
import java.util.List;
/**
* @author linjiazeng
* @version 1.0
* @date 2020/12/28 22:29
**/
public class ExcelUtil {
/**
* 导出
* @param response
* @param data
* @param fileName
* @param sheetName
* @param clazz
* @throws Exception
*/
public static void writeExcel(HttpServletResponse response, List<? extends Object> data, String fileName, String sheetName, Class clazz) throws Exception { //表头样式
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
//设置表头居中对齐
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//内容样式
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//设置内容靠左对齐
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
EasyExcel.write(getOutputStream(fileName, response), clazz).excelType(ExcelTypeEnum.XLSX).sheet(sheetName).registerWriteHandler(horizontalCellStyleStrategy).doWrite(data); }
private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
fileName = de(fileName, "UTF-8");
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
response.addHeader("Access-Control-Expose-Headers", "Content-disposition");
OutputStream();
}
}
调⽤⼯具类下载模板
/*下载模板*/
@GetMapping("/download/template")
public void downloadTemplate(HttpServletResponse response){
String fileName = "导⼊讲师模板";
String sheetName="导⼊讲师模板";
List<TeacherExcel> teacherExcelList = new ArrayList<>();
TeacherExcel teacherExcel = new TeacherExcel();
teacherExcel.setName("ljz");
teacherExcel.setIntro("清华毕业,⾼材⽣");
teacherExcel.setCareer("资深讲师");
teacherExcel.setSort(1);
teacherExcel.setLevel(1);
teacherExcelList.add(teacherExcel);
try {
/
/TeacherExcel.class对应你的模板类
//teacherExcelList模板的例⼦
//也可以使⽤这种⽅式导出你查询出数据excel⽂件
ExcelUtil.writeExcel(response,teacherExcelList,fileName,sheetName,TeacherExcel.class);
} catch (Exception e) {
System.out.Cause());
}
}
效果:
有问题可以互相交流,也可以去EasyExcel官⽹学习
到此这篇关于Spring Boot整合EasyExcel(完整版包含上传解析excel和下载模板)的⽂章就介绍到这了,更多相关SpringBoot整合EasyExcel内容请搜索
以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论