当前位置:网站首页>Development techniques - import files using easyexcel (simple example)
Development techniques - import files using easyexcel (simple example)
2022-06-30 21:49:00 【JustDI-CM】
Catalog
1. Introduce dependencies
pom Add to file easyexcel rely on
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.0.0</version>
</dependency>2. Entity class
The fields in the entity class correspond to the columns in the table to be imported one by one .
import com.alibaba.excel.annotation.ExcelProperty;
public class TestImport {
@ExcelProperty(value = " Serial number ", index = 0)
private String id;
@ExcelProperty(value = " full name ", index = 1)
private String name;
@ExcelProperty(value = " Age ", index = 2)
private String age;
public TestImport() {
}
public TestImport(String id, String name, String age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "TestImport{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
}
3. Business processing class
Interface
import Your path .TestImport;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
public interface FileService {
void dealFile(MultipartFile file);
void save(List<TestImport> list);
}
Implementation class
import com.alibaba.excel.EasyExcel;
import Your path .TestImport;
import Your path .FileListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
@Component
public class FileServiceImpl implements FileService {
private static final Logger LOGGER = LoggerFactory.getLogger(FileServiceImpl.class);
@Autowired
private FileService fileService;
@Override
public void dealFile(MultipartFile file) {
InputStream is = null;
try {
is = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
//1. Read the data ,TestImport It is my pojo class ,
//2.new SorageListener(storageService) This is a monitor , Mainly used to read data , Don't worry. I'll talk about it later
//3. Special note storageService This service, I have an injection on it @Autowired, Remember not to new Will report a mistake
EasyExcel.read(is, TestImport.class, new FileListener(fileService)).sheet().doRead();
}
@Override
public void save(List<TestImport> list) {
LOGGER.info(" Unloading start ------");
// Write the drop logic , Omitted here
}
}
4. Monitor class
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import Your path .FileService;
import Your path .FileServiceImpl;
import Your path .TestImport;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
@Component
public class FileListener extends AnalysisEventListener<TestImport> {
private static final Logger LOGGER = LoggerFactory.getLogger(FileListener.class);
// Read data initialization value
private static final int BATCH_COUNT = 50;
List<TestImport> list = new ArrayList<>();
private FileService fileService;
public FileListener() {
fileService =new FileServiceImpl();
}
public FileListener(FileService fileService) {
this.fileService = fileService;
}
/**
* Every data parsing will call , The data is parsed one by one
*
* @param data one row value. Is is same as {@link AnalysisContext#readRowHolder()}
* @param context
*/
@Override
public void invoke(TestImport data, AnalysisContext context) {
LOGGER.info("invoke--- Start parsing table data ");
list.add(data);
// achieve BATCH_COUNT 了 , Need to store the database once , Prevent tens of thousands of data in memory , Easy to OOM
if (list.size() >= BATCH_COUNT) {
LOGGER.info("invoke--- Over the set value , Import database ");
saveData();
// Storage complete cleaning list
list.clear();
}
}
/**
* all excel The data analysis in the table is completed Will call this
* Explain why you want to save data ?
* The number of initialization reads is 50, The information in the table has been loaded ,,
* hypothesis excel At the end of the table, only 30 Row legacy data , So to prevent the existence of legacy data Try to judge whether the next set is empty ,
* It is not empty and is being stored ( This is my logic to judge , If it is not necessary, it can also be judged )
* @param context
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
LOGGER.info("doAfterAllAnalysed--- Start to deal with ");
if(list.size()==0){
return;
}
saveData();
LOGGER.info(" All data analysis completed !");
}
/**
* Plus the storage database
*/
public void saveData() {
// The code implementation class layer saves data
fileService.save(list);
LOGGER.info(" Storage database success !");
}
}
5.controller
//excel Bulk import data
@PostMapping(value = "/import")
public T storageService(@RequestParam("file") MultipartFile file) {
T t= new T();
try {
fileService.dealFile(file);
} catch (Exception e) {
return t;
}
return t;
}
// This T Is the return type 6.postman test

7. explain
See through the output log , Request to come in , Business processing class calls dealFile() perform EasyExcel.read , Then enter the listening class , Execute first invoke() Re execution doAfterAllAnalysed()

Write this right for record
边栏推荐
- Pytorch quantitative perception training (qat) steps
- Akk bacteria - the next generation of beneficial bacteria
- 给苏丹国安德森苏丹的撒过 d s g
- 漫谈Clickhouse Join
- ca i啊几次哦啊句iu家哦
- 12345
- Some problems when SSH default port is not 22
- jupyterbook 清空控制台输出
- Arcmap|assign values to different categories of IDS with the field calculator
- sdfsdf
猜你喜欢

Prediction and regression of stacking integrated model

5G 在智慧医疗中的需求

谈谈数字化转型的几个关键问题

A comprehensive understanding of gout: symptoms, risk factors, pathogenesis and management

Pytorch quantitative practice (2)

興奮神經遞質——穀氨酸與大腦健康

pytorch geometric torch-scatter和torch-sparse安装报错问题解决
一文读懂什么是MySQL索引下推(ICP)

Deployment and use of Nacos

Nacos部署及使用
随机推荐
"Trust machine" empowers development
1-10 根据不同的url响应客户端的内容
1-19 using CORS to solve interface cross domain problems
Go Web 编程入门: 一探优秀测试库 GoConvey
Markdown notes concise tutorial
谈谈数字化转型的几个关键问题
1-11 create online file service
Phoenix architecture: an architect's perspective
1-21 jsonp interface
测试媒资缓存问题
Develop your own package
1-3 using SQL to manage databases
Reading notes of Clickhouse principle analysis and Application Practice (1)
VIM common shortcut keys
ClickHouse distributed表引擎
Ml & DL: introduction to hyperparametric optimization in machine learning and deep learning, evaluation index, over fitting phenomenon, and detailed introduction to commonly used parameter adjustment
sdfsdf
布隆过滤器
ML&DL:機器學習和深度學習中超參數優化的簡介、評估指標、過擬合現象、常用的調參優化方法之詳細攻略
twelve thousand three hundred and forty-five