Springboot下使用easyExcel玩转Excel表的导出
https://blog.csdn.net/LemonSnm/article/details/106394075
在前面的导出项目里继续添加导入功能,直接放代码:
该监听器可以验证
①导入excel表模板的表头是否正确
②导入的数据类型是否正确
③若错误 返回错误位置信息
④正确导入,则返回对应的List<>集合
⑤返回的最终结果 : 包含 isCorrectFormat:解析是否正确,resultMessage:解析结果提示信息,list:解析数据列表
package com.sinocontact.utils.easyexcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.Head;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 监听器工具类
* @author lemon
* @since 2020/5/26 0026
*/
@Service
public class EasyExcelListener extends AnalysisEventListener {
private static final Logger logger = LoggerFactory.getLogger(EasyExcelListener.class);
private Map headMap = new HashMap<>(); // 导入模板头内容
private boolean isCorrectFormat= true; //结果标记 默认错误
private String resultMessage= ""; //结果信息
private List list = new ArrayList(); //导入Excel数据内容
public EasyExcelListener(){
}
/*
*/
/*自定义头*//*
public EasyExcelListener(Map headMap){
this.headMap = headMap;
}
*/
/*监听读取导入表的每一行数据*/
public void invoke(T object, AnalysisContext analysisContext) {
if(!isCorrectFormat){ //格式是否正确
return;
}
logger.info("解析到一条数据:{}", object);
list.add(object); //加入list
}
/* 最终都会执行的方法 */
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
if(isCorrectFormat){ //表头是否正确
resultMessage = "导入所有数据完成!";
logger.info("导入解析所有数据完成!");
}
}
/**
* 返回头数据,可以处理头文件
*
*/
@Override
public void invokeHeadMap(Map headMap, AnalysisContext context) {
//是否手动传入表头信息 没有则自动读取实体类头信息
try {
if(this.headMap == null || this.headMap.size() <= 0){
Map map = context.currentReadHolder().excelReadHeadProperty().getHeadMap();
for (int i = 0; i < map.size(); i++) {
//封装成headMap
this.headMap.put(map.get(i).getColumnIndex(),map.get(i).getHeadNameList().get(0));//加入模板头
}
}
}catch (Exception e){
isCorrectFormat = false; //导入错误
resultMessage = "导入失败,请联系管理员!";
logger.info("未自定义Excel头信息,自动读取实体类注解的头信息,缺少注解name或index值!",e);
return;
}
logger.info("导入的表头:" + headMap);
logger.info("模板的表头:" + this.headMap);
if(this.headMap == null || headMap == null || this.headMap.size() != headMap.size()){
isCorrectFormat = false; //导入表头错误
resultMessage = "导入表的表头与模板表头不符!";
logger.info("导入表的表头与模板表头不符!");
}else {
for (int i = 0; i < this.headMap.size(); i++) { //循环遍历判断表格头是否一一对应
if(!this.headMap.get(i).equals(headMap.get(i))){
isCorrectFormat = false; //导入表头错误
resultMessage = "导入表的表头与模板表头不符!";
logger.info("导入表的表头与模板表头不符!");
break;
}
}
}
}
/**
* 在转换异常 获取其他异常下会调用本接口。抛出异常则停止读取。如果这里不抛出异常则 继续读取下一行。
*/
@Override
public void onException(Exception exception, AnalysisContext analysisContext) {
// logger.error("解析失败,但是继续解析下一行:{}", exception.getMessage());
// 如果是某一个单元格的转换异常 能获取到具体行号
// 如果要获取头的信息 配合invokeHeadMap使用
if (exception instanceof ExcelDataConvertException) { //表格内容转换异常
ExcelDataConvertException excelException = (ExcelDataConvertException)exception;
logger.error("第{}行,第{}列解析异常", excelException.getRowIndex() + 1, excelException.getColumnIndex() + 1);
resultMessage = "第" + (excelException.getRowIndex() + 1) + "行,第" + (excelException.getColumnIndex() + 1) + "列,内容格式错误!";
list.clear();
}else {
logger.error("导入解析异常!",exception);
resultMessage = "导入异常!,请联系管理员";
list.clear();
isCorrectFormat = false;
}
}
public List getList() {
return list;
}
public Map getHeadMap() {
return headMap;
}
public void setHeadList(Map headMap) {
this.headMap = headMap;
}
public boolean isCorrectFormat() {
return isCorrectFormat;
}
public String getResultMessage() {
return resultMessage;
}
public void setCorrectFormat(boolean correctFormat) {
isCorrectFormat = correctFormat;
}
public void setResultMessage(String resultMessage) {
this.resultMessage = resultMessage;
}
}
package com.lemon.entity;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelIgnoreUnannotated;
import com.alibaba.excel.annotation.ExcelProperty;
/**
* 学生类
* @author lemon
* @since 2020-05-26
*/
@ExcelIgnoreUnannotated()
public class Student {
@ExcelIgnore //忽略此字段
private Integer myId;
@ExcelProperty(value = "学号",index = 0) //0 对应导出Excel表格的第一列
private Integer id;
@ExcelProperty(value = "姓名",index = 1)
private String name;
@ExcelProperty(value = "性别",index = 2)
private String sex;
@ExcelProperty(value = "班级",index = 3)
private String grade;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", grade='" + grade + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
这里自己模拟获取本地文件输入流,可以其他方式获取
package com.lemon.controller;
import com.alibaba.excel.EasyExcel;
import com.lemon.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
/**
*
* @author lemon
* @since 2020/6/10 0010
*/
@Controller
public class TestExport {
@RequestMapping("/export")
public void export() throws FileNotFoundException {
//模拟导入表格 输入流
String fileName = "E:\\aa.xlsx"; //模拟文件名
FileInputStream fis = new FileInputStream(fileName); //模拟输入流
EasyExcelListener listener = new EasyExcelListener();
EasyExcel.read( fis, Student.class, listener).sheet().doRead();
System.out.println("解析的状态:" + listener.isCorrectFormat());
System.out.println("数据解析状态信息:" + listener.getResultMessage());
System.out.println("解析的数据:" + listener.getList());
}
}
http://localhost:8081/export
控制台打印效果: