当前位置:网站首页>Easyexcel learning notes
Easyexcel learning notes
2022-06-28 18:21:00 【Laughing shrimp】
EasyExcel Learning notes
- pom.xml Add dependency
- Test data
- The simplest reading
- More clothes ( skip N That's ok )
- Read multiple sheet
- Synchronous return
- Read header data
- Additional information ( Comments 、 Hyperlinks 、 Merge cell information read )
- Read formulas and cell types
- Do not create a read of the object
- Reference material
It is basically the official quick start , I walked once by myself , And notes . Not completely copying the official example , Just to make a comparison .
pom.xml Add dependency
In addition, for convenience, the fastjson 2.0.3, lombok 1.18.24, junit 4.11
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.0</version>
</dependency>
Test data
The test of excel Put it here :
private String filePath = "E:\\temp\\ Test data .xlsx";
Entity class
- @ExcelProperty Fields can be set .
| usage | explain |
|---|---|
@ExcelProperty(index = 0) | Specifies the name of the column Indexes |
@ExcelProperty(" Date title ") | Appoint Name |
@ExcelProperty(converter = CustomStringStringConverter.class) | Custom converter |
@DateTimeFormat("yyyy-MM-dd HH:mm:ss") | string Followed by the formatted date |
@NumberFormat("#.##%") | string Followed by formatted percentage figures |
@Data
@EqualsAndHashCode
public class DemoData {
// @ExcelProperty(index = 0)
private String string;
// @ExcelProperty(" Date title ")
private Date date;
// @DateTimeFormat("yyyy-MM-dd HH:mm:ss")
// private String dateStr;
private Double doubleData;
}
Custom converter
public class CustomStringStringConverter implements Converter<String> {
@Override
public Class<?> supportJavaTypeKey() {
return String.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
/** When reading here, it will call */
@Override
public String convertToJavaData(ReadConverterContext<?> context) {
return " Customize :" + context.getReadCellData().getStringValue();
}
/** This is called when writing */
@Override
public WriteCellData<?> convertToExcelData(WriteConverterContext<String> context) {
return new WriteCellData<>(context.getValue());
}
}
The simplest reading
How to write it 1
- We use our own monitors PageReadListener , It reads every time
BATCH_COUNT = 100Data . Then consume . invoke: eachThat's okAfter reading, it will call .doAfterAllAnalysed: EverysheetAfter reading, it will call .- When we create it, we need to send it to consumers
Consumer<List<T>> consumer.(invoke、doAfterAllAnalysedWill invoke the consumer ) - You need to specify the entity type to be used
DemoData.class, Readsheet( Default index0) after , The file stream closes automatically . - The following is an example of the official website , I just adjusted the writing :
@Test
public void simpleRead() {
// This consumer is PageReadListener Of invoke、doAfterAllAnalysed Will be called in .
Consumer<List<DemoData>> consumer = dataList -> {
dataList.forEach(demoData -> log.info(" Read a piece of data {}", JSON.toJSONString(demoData)));
};
// Create a listener with the consumer above
PageReadListener<DemoData> myListener = new PageReadListener<>(consumer);
// Start reading
EasyExcel.read(fileName, DemoData.class, myListener).sheet().doRead();
}
How to write it 2
- Direct use
An anonymous classRealization ReadListener Interface . Rewroteinvoke、doAfterAllAnalysedThese two methods are OK . - Official sample code A little longer : A little .
How to write it 3
Named class Realization ReadListener Interface gets a listener . And the top is just Named class And An anonymous class The difference between .
How to write it 4
One file one ExcelReader
// The listener in the previous article is directly used here myListener
try (ExcelReader excelReader = EasyExcel.read(fileName, DemoData.class, myListener ).build()) {
// Construct a sheet Here you can specify the name or index ( Notice that the index I gave is the second sheet)
ReadSheet readSheet = EasyExcel.readSheet(1).build();
// Read this sheet
excelReader.read(readSheet);
}
More clothes ( skip N That's ok )
If the header has multiple lines , Then you can specify how many lines to skip , Start reading .
Just add one headRowNumber Used to indicate how many lines there are in the header .
@Test
public void headRead() {
EasyExcel.read(filePath, new NoModelDataListener()).sheet().headRowNumber(7).doRead();
}
Read multiple sheet
To save space, I used it directly here PageReadListener.
Here we need to pay attention to : Every sheet Once I read it, I called it doAfterAllAnalysed.
Because there is only one listener here , At last all sheet Will be written into the same Monitor in .( The visual effect is that each output of the following code contains the last content . People understand that it is necessary to process data , After reading the last sheet It would be better to deal with it together .)
Read all sheet
EasyExcel.read(fileName, DemoData.class, new PageReadListener<>(dataList -> {
dataList.forEach(demoData -> log.info(" Read a piece of data {}", JSON.toJSONString(demoData)));
})).doReadAll();
Read the part sheet
Read here The first 1 And The first 3 Tables , Every sheet Corresponding to Monitor , So it is output separately .
If you use the same Monitor , The effect is the same as above .
// Monitor
Consumer<List<DemoData>> consumer = dataList -> {
dataList.forEach(demoData -> log.info(" Read a piece of data {}", JSON.toJSONString(demoData)));
};
// Use the monitor above , Generate ReadSheet list .( The first 1、 The first 3 individual Sheet)
List<ReadSheet> sheets = Stream.of(0, 2)
.map(i -> EasyExcel.readSheet(i)
.head(DemoData.class)
.registerReadListener(new PageReadListener<>(consumer))
.build())
.collect(Collectors.toList());
// Read sheets In the table
try (ExcelReader excelReader = EasyExcel.read(fileName).build()) {
excelReader.read(sheets);
}
Synchronous return
And The simplest reading The only difference is that doRead Switch to doReadSync.
The following is without head(DemoData.class) Writing . Direct use List<Map<Integer, String>> Pick up .
List<Map<Integer, String>> objects = EasyExcel.read(fileName).sheet().doReadSync();
objects.forEach(demoData -> log.info(" Read a piece of data {}", JSON.toJSONString(demoData)));
Read header data
Too lazy to implement a listener from scratch , Direct use SyncReadListener make carbon copies nvokeHeadMap .
I've set it up here headRowNumber(3) Head has 3 That's ok .
SyncReadListener syncReadListener = new SyncReadListener() {
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
log.info(" Parse to a header data :{}", JSON.toJSONString(headMap));
}
};
EasyExcel.read(fileName, DemoData.class, syncReadListener).sheet().headRowNumber(3).doRead();
Additional information ( Comments 、 Hyperlinks 、 Merge cell information read )
Official website sample code It is a bit long to judge and process by type , I'll just output it directly .
Also steal a lazy rewrite SyncReadListener Direct use .
SyncReadListener syncReadListener = new SyncReadListener() {
@Override
public void extra(CellExtra extra, AnalysisContext context) {
log.info("\n Types of additional information ( Comments 、 Hyperlinks 、 merge cell ) yes :{};" +
"\n That's ok :{}, Column {};\n Go ahead :{}, Start the column {};\n End line :{}, End example :{};\n The content is :{}",
extra.getType(),
extra.getRowIndex(), extra.getColumnIndex(),
extra.getFirstRowIndex(), extra.getFirstColumnIndex(),
extra.getLastRowIndex(), extra.getLastColumnIndex(),
extra.getText());
}
};
// All three kinds of additional information are not read by default , Need to be manually added .
EasyExcel.read(fileName, null, syncReadListener)
.extraRead(CellExtraTypeEnum.COMMENT)// Read comments
.extraRead(CellExtraTypeEnum.HYPERLINK)// Read hyperlinks
.extraRead(CellExtraTypeEnum.MERGE).sheet().doRead();// Read merged cell information
Read formulas and cell types
The key is that the font in the entity is CellData Package , You can get the cell information .
Be careful : The field order should correspond to the table column
@Data
@EqualsAndHashCode
@JSONType(orders = {
"string", "date", "doubleData", "formulaValue"}) // Set the next order to look better
public class CellDataReadDemoData {
private CellData<String> string;
private CellData<Date> date; // excel The date value in is actually a number
private CellData<Double> doubleData;
private CellData<String> formulaValue; // It may not be perfect , Wait for the official follow-up
}
List<CellDataReadDemoData> objects = EasyExcel.read(fileName).head(CellDataReadDemoData.class).sheet().doReadSync();
objects.forEach(demoData -> log.info(" Parse to a piece of data {}", JSON.toJSONString(demoData)));
The contents of the table here

This is the effect of one line
{
"string":{
"data":" character string 0","dataFormatData":{
"format":"General","index":0},"stringValue":" character string 0","type":0
},
"date":{
"data":"2022-06-27 00:00:00","dataFormatData":{
"format":"yyyy/m/d","index":14},"numberValue":44739.0,"type":2
},
"doubleData":{
"data":1.0,"dataFormatData":{
"format":"General","index":0},"numberValue":1.0,"type":2
},
"formulaValue":{
"data":" character string 0447391","dataFormatData":{
"format":"General","index":0},
"formulaData":{
"formulaValue":"A2&B2&C2"},"stringValue":" character string 0447391","type":0
}
}
Do not create a read of the object
Create fields by table normally , Create entities , Then read the data , There's nothing to say . Take a look here : Do not create a read of the object
Monitor
Is the official code , Just added a note .
package com.jerry.excel.listener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.Map;
@Slf4j
public class NoModelDataListener extends AnalysisEventListener<Map<Integer, String>> {
/** * every other 5 Storage database , It can be used in practice 100 strip , Then clean up list , Convenient for memory recycling */
private static final int BATCH_COUNT = 5;
private List<Map<Integer, String>> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
/** * After each row is read, the * @param data Current line data * @param context */
@Override
public void invoke(Map<Integer, String> data, AnalysisContext context) {
log.info(" Parse to a piece of data :{}", JSON.toJSONString(data));
cachedDataList.add(data);
if (cachedDataList.size() >= BATCH_COUNT) {
saveData();
cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
/** * Every sheet After reading, it will call */
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
saveData();
log.info(" All data analysis completed !");
}
/** * Write to database operation */
private void saveData() {
log.info("{} Data , Start storing the database !", cachedDataList.size());
log.info(" Storage database success !");
}
}
Test code
This note is also official , It seems that there are fewer words .
@Test
public void noModelRead() {
// here as long as , Then read the first sheet Synchronous reading will automatically finish
EasyExcel.read(filePath, new NoModelDataListener()).sheet().doRead();
}
Reference material
Easy Excel Official website
Easy Excel Official documents : Quick start ( Regular operation here , Just do it )
Easy Excel Official documents : read excel- General parameters
边栏推荐
- moco挡板制作及运行成功
- kubernetes资源对象介绍及常用命令
- 数据库实验7 完整性约束
- How to create a CSR (certificate signing request) file?
- 杂记:数据库go,begin,end,for,after,instead of
- EasyExcel 学习笔记
- Applet graduation project reservation based on wechat housekeeping service applet graduation project opening report function reference
- 通达信能开户炒股吗?安全吗?
- 单片机修改网络硬件驱动(phy芯片更换)
- Small program graduation project based on wechat mobile mall small program graduation project opening report function reference
猜你喜欢

2022 chemical automation control instrument test simulation 100 questions simulation test platform operation
![抓包整理外篇fiddler————了解工具栏[一]](/img/f4/fa909f30c0097fb77cea10eb0d3109.png)
抓包整理外篇fiddler————了解工具栏[一]

kubeadm创建kubernetes集群

工业数字化与新一代数字化系统设计平台----讲座

Redis6笔记04 主从复制,集群,应用问题,Redis6新功能

China gaobang brand story: standing guard for safety, gaobang pays attention to

CSDN Blogger

MCU modifies network hardware driver (PHY chip replacement)

HackTheBox-baby CachedView

Node foundation ~ node level
随机推荐
DMS的SQL结果集导出支持传参数吗?
Use PEGA to develop a simple RPA program
kubernetes可视化界面dashboard
How to create a CSR (certificate signing request) file?
第2章 处理文件、摄像头和图形用户界面cameo应用
Spark调优(提交作业资源参数调优)
东方财富软件股票开户是靠谱的吗?在哪开户安全
The fourth largest operator cannot be a "catfish"
图形系统——2.view绘制
2022 practice questions and mock examination of Shandong Province safety officer C certificate examination
2022A特种设备相关管理(电梯)特种作业证考试题库及在线模拟考试
Cann media data processing V2, jpegd interface introduction
Introduction to apifox
Pure big resentment! Those who were discouraged from taking the postgraduate entrance examination
Does face recognition test involve privacy and security issues? A foreign company was urgently stopped
如何使用 SAP CDS view 中的 currency conversion 功能
HTNL简介
Small program graduation project based on wechat milk tea takeout mall small program graduation project opening report function reference
2022 recurrent training question bank and online simulation examination for main principals of hazardous chemicals business units
MCU modifies network hardware driver (PHY chip replacement)