当前位置:网站首页>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
边栏推荐
- 1-12 初步认识Express
- 12345
- Excitatory neurotransmitter glutamate and brain health
- jupyterbook 清空控制台输出
- PyTorch量化实践(1)
- Testing media cache
- Reading notes of Clickhouse principle analysis and Application Practice (2)
- 模板方法模式介绍与示例
- A group of K inverted linked lists
- Ssh server configuration file parameter permitrootlogin introduction
猜你喜欢

Markdown notes concise tutorial

Anaconda下安装Jupyter notebook

Inventory the six second level capabilities of Huawei cloud gaussdb (for redis)

It is urgent for enterprises to protect API security

介绍一款|用于多组学整合和网络可视化分析的在线平台

阿婆做的臭豆腐

本地浏览器打开远程服务器上的Jupyter Notebook/Lab以及常见问题&设置

pytorch geometric torch-scatter和torch-sparse安装报错问题解决

Summary of errors reported when using YML file to migrate CONDA environment

1-2 install and configure MySQL related software
随机推荐
介绍一款|用于多组学整合和网络可视化分析的在线平台
1-19 利用CORS解决接口跨域问题
微服務鏈路風險分析
漫谈Clickhouse Join
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
1-21 JSONP接口
艾芬医生事件解析
Introduction and example of template method mode
Introduce an online platform for multi omics integration and network visual analysis
ca i啊几次哦啊句iu家哦11111
It is urgent for enterprises to protect API security
《ClickHouse原理解析与应用实践》读书笔记(1)
测试媒资缓存问题
Inventory the six second level capabilities of Huawei cloud gaussdb (for redis)
Analysis of doctor Aifen's incident
FreeRTOS record (IX. an example of a bare metal project transferring to FreeRTOS)
兴奋神经递质——谷氨酸与大脑健康
模板方法模式介绍与示例
Introduction to go web programming: a probe into the excellent test library gocovey
Pytorch quantitative practice (2)