当前位置:网站首页>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
边栏推荐
- 京东与腾讯续签三年战略合作协议;起薪涨至26万元,韩国三星SK争相加薪留住半导体人才;Firefox 102 发布|极客头条
- 1-11 create online file service
- Anaconda下安装Jupyter notebook
- 1-2 安装并配置MySQL相关的软件
- twelve thousand three hundred and forty-five
- ClickHouse distributed表引擎
- Clickhouse native monitoring item, system table description
- Neurotransmetteurs excitateurs - glutamate et santé cérébrale
- 1-18 create the most basic express server & API module for creating routes
- Summary of errors reported when using YML file to migrate CONDA environment
猜你喜欢

Five years after graduation, I wondered if I would still be so anxious if I hadn't taken the test
![[untitled]](/img/42/47a8c8faaed33a1d9e864cb2ef7b72.png)
[untitled]
Understand what MySQL index push down (ICP) is in one article

《ClickHouse原理解析与应用实践》读书笔记(2)
笔记【JUC包以及Future介绍】

程序员女友给我做了一个疲劳驾驶检测

AKK菌——下一代有益菌

Usbcan analyzer's supporting can and canfd comprehensive test software lkmaster software solves engineers' can bus test problems

Clickhouse native monitoring item, system table description

Jupyter notebook/lab switch CONDA environment
随机推荐
艾芬医生事件解析
1-20 pre inspection request
ML&DL:機器學習和深度學習中超參數優化的簡介、評估指標、過擬合現象、常用的調參優化方法之詳細攻略
qsort函数和模拟实现qsort函数
1-15 nodemon
Installing jupyter notebook under Anaconda
1-16 路由的概念
Ssh server configuration file parameter permitrootlogin introduction
做一个 Scrollbar 的思考
激发新动能 多地发力数字经济
顺祝老吴的聚会
开发属于自己的包
sdfsdf
测试媒资缓存问题
ClickHouse distributed表引擎
Encryption and decryption and the application of OpenSSL
看阿里云 CIPU 的 10 大能力
测试勋章1234
Analysis of doctor Aifen's incident
[backtracking] full arrangement leetcode46