easyexcel导入Excel
程序员文章站
2022-06-24 19:06:42
easyexcel导入controller@RequestMapping(value = "/read",method = RequestMethod.POST)@ResponseBodypublic String readExcel(@RequestParam("readExcel") MultipartFile file) { try { /** * Build excel the read * * @param i...
easyexcel导入
controller
@RequestMapping(value = "/read",method = RequestMethod.POST)
@ResponseBody
public String readExcel(@RequestParam("readExcel") MultipartFile file) {
try {
/**
* Build excel the read
*
* @param inputStream
* Input stream to read.
* 输入要读取的流
* @param head
* Annotate the class for configuration information.
* 每行存储的实体类型
* @param readListener
* Read listener.
* 读监听器,每读一行内容都会调用一次该对象的invoke,在invoke中可以操作读取到的数据
* @return Excel reader builder.
*/
//获得工作簿
ExcelReaderBuilder read = EasyExcel.read(file.getInputStream(), ReadFile.class, new ExcelListener());
//获得工作表 又两种形形式可以通过下标也可以通过名字2003Excel不支持名字
ExcelReaderSheetBuilder sheet = read.sheet();
//进行读操作
sheet.doRead();
return "ok";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
listener
package com.cat.youth_learning.Listener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.cat.youth_learning.mapper.YouthMapper;
import com.cat.youth_learning.pojo.ReadFile;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
/**
* EasyExcel 导入监听
*/
public class ExcelListener extends AnalysisEventListener<ReadFile> {
private final Integer MAX_LIST_SIZE=5;
List<ReadFile> list=new ArrayList<>();
publicExcelListener(YouthMapper youthMapper) {
this.youthMapper = youthMapper;
}
@Autowired
YouthMapper youthMapper;
/**
* @param data
* @param context
*/
@Override
public void invoke(ReadFile data, AnalysisContext context) {
list.add(data);
if (list.size()%MAX_LIST_SIZE==0){
savelist();
list.clear();
}
}
/**
* 读取文档后调用的方法
* @param context
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
//将剩余的也添加
savelist();
}
}
private void saveData() {
System.out.println(list.size()+"条数据,开始存储数据库!");
System.out.println(list);
}
本文地址:https://blog.csdn.net/wildcata/article/details/109615096