当前位置:网站首页>Import export simple
Import export simple
2022-06-26 06:12:00 【Source code Xiao Liu】
EasyExcel It's based on Java Simple 、 Save memory for reading and writing Excel Open source projects for
There are basically two ways to read and write
- By creating objects
- Do not create objects for operation
Import dependence :
<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.0.5</version>
</dependency>This article will myql in city Table as read / write demo Data source
Mode one : Don't create objects
write in Excel
mybatis: Statement writing
<sql id="exportSql">
c.ID " City Numbers ",c.Name " The city name ",c.CountryCode " City Code ",
c.District " Geographical area ",
c.Population " population size ",
status " state ",sex " Gender ",birthday " Birthday ",createTime " Time "
</sql>
<select id="getAll" parameterType="map" resultType="map">
select
<include refid="exportSql"/>
from city as c
</select>Data needs to be processed :
/**
* Do not create objects to get data
*
* @return
*/
private List<List<Object>> dataList2() {
List<List<Object>> list = new ArrayList<List<Object>>();
List<Map<String, Object>> all = cityDao.getAll();
all.forEach(t -> {
Map<String, Object> t1 = t;
List<Object> data = new ArrayList<Object>();
List<List<String>> lists = head2();
lists.forEach(s -> {
Object o = t1.get(s.get(0));
if (o instanceof Date) { // Time type cannot be processed , Go straight to String type
String s1 = String.valueOf(o);
o=s1;
}
data.add(o);
});
list.add(data);
});
return list;
}
/**
* excel The first line of data
*
* @return
*/
private List<List<String>> head2() {
List<String> strings = Arrays.asList(new String[]
{" City Numbers ", " The city name ", " City Code ", " Geographical area ", " population size ", " state ", " Gender ", " Birthday ", " Time "});
List<List<String>> list = new ArrayList<List<String>>();
strings.forEach(t -> {
list.add(Collections.singletonList(t));
});
return list;
}test :
/**
* Simple export without creating objects -----------------------------------
*/
@Test
public void exportByData() {
// dataList2();
String file = "C:\\Users\\lhl\\Desktop\\tem.xlsx";
EasyExcel.write(file).head(head2()).sheet(" Templates ").doWrite(dataList2());
}
result : There is too much data below, so don't expand it 
Read Excel
Create a listening class : Every row of data is read
public class NoModelDataListener extends AnalysisEventListener<Map<Integer, Object>> {
/**
* every other 100 Storage database , It can be used in practice 3000 strip , Then clean up list , Convenient for memory recycling
*/
private static final int BATCH_COUNT = 100;
List<Map<Integer, Object>> list = new ArrayList<Map<Integer, Object>>();
@Override
public void invoke(Map<Integer, Object> data, AnalysisContext context) {
System.out.println("---------------- Read excel data -------------------------");
System.out.println(data);
list.add(data);
if (list.size() >= BATCH_COUNT) {
saveData();
list.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
saveData();
}
/**
* Plus the storage database
*/
private void saveData() {
System.out.println(" Storage database ");
}
@Test
public void fadfda(){
// System.out.println("hello world !!!");
try {
// Create a URL example
URL url = new URL("https://mp.weixin.qq.com/s/ZGjVb3gwYuj3mGv0sCyAbw");
try {
// adopt URL Of openStrean Method to get URL The voluntary byte input stream represented by the
InputStream is = url.openStream();
InputStreamReader isr = new InputStreamReader(is,"utf-8");
// Add a buffer to the character input stream
BufferedReader br = new BufferedReader(isr);
String data = br.readLine();// Reading data
while (data!=null){// Loop read data
System.out.println(data);// Output data
data = br.readLine();
}
br.close();
isr.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}test :
/**
* Read excel
*/
@Test
public void readExcelByNoObj(){
// here as long as , Then read the first sheet Synchronous reading will automatically finish
String file = "C:\\Users\\lhl\\Desktop\\tem.xlsx";
EasyExcel.read(file, new NoModelDataListener()).sheet().doRead();
}effect :

excel Easy read to this , There is no complicated processing . When we encounter complex data processing , It is more important to create objects to implement excel Data import and reading .
Mode two : Create objects
write in Excel
Create entity class :ExportExcel,get 、set The method will not repeat
@ContentRowHeight(10)
@HeadRowHeight(20)
@ColumnWidth(25)
public class ExportExcel {
@ExcelProperty(" City Numbers ")
private Integer id;
@ExcelProperty(" The city name ")
private String name;
/**
* Width is 50
*/
// @ColumnWidth(50) It can be set in a single column
@ExcelProperty(" City Code ")
private String countryCode;
@ExcelProperty(" region ")
private String district;
@ExcelProperty(" Population ")
private Integer population;
@ExcelProperty(" state ")
private Integer status;
@ExcelProperty(" Gender ")
private String sex;
@DateTimeFormat("yyyy year MM month dd Japan ")
@ExcelProperty(" Birthday ")
private Date birthday;
@DateTimeFormat("yyyy year MM month dd Japan HH when mm branch ss second ")
@ExcelProperty(" Time ")
private Date createTime;
...................................
}test : The effect is the same , I won't repeat
mybatis layer :sql Is to query all the information that will not be repeated :
/**
* ---------------------------------------------
* Create an object export ----- Very convenient
*/
@Test
public void fdsasfa() {
List<ExportExcel> list = cityDao.exportAll();
String file = "C:\\Users\\lhl\\Desktop\\tem.xlsx";
EasyExcel.write(file, ExportExcel.class).sheet(" Templates ").doWrite(list);
}Read Excel
Create a listening class :
// There is a very important point ModelDataListener Can not be spring management , Every time you read excel Both new, And then it uses spring You can construct methods to pass in
public class ModelDataListener extends AnalysisEventListener<ExportExcel> {
/**
* every other 5 Storage database , It can be used in practice 3000 strip , Then clean up list , Convenient for memory recycling
*/
private static final int BATCH_COUNT = 5;
List<ExportExcel> list = new ArrayList<ExportExcel>();
private CityDao cityDao;// You can operate the database to store data
public ModelDataListener(CityDao demoDAO) {
System.out.println("------- This gets the incoming dao layer -------");
List<ExportExcel> all = demoDAO.exportAll();
all.forEach(t-> System.out.println(t));
this.cityDao=demoDAO;
}
/**
* Every data parsing will call
* @param data
* one row value. Is is same as {@link AnalysisContext#readRowHolder()}
*/
@Override
public void invoke(ExportExcel data, AnalysisContext analysisContext) {
// System.out.println(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) {
saveData();
// Storage complete cleaning list
list.clear();
}
}
/**
* All data analysis is done Will call
*
* @param context
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// We also need to save data here , Make sure that the last legacy data is also stored in the database
saveData();
}
/**
* Plus the storage database
*/
private void saveData() {
}
}
test : Results the correct
/**
* Read according to the created object
*/
@Test
public void readByModel(){
String file = "C:\\Users\\lhl\\Desktop\\tem.xlsx";
// here You need to specify which to read class To read , Then read the first sheet The file stream closes automatically
EasyExcel.read(file, ExportExcel.class, new ModelDataListener(cityDao)).sheet().doRead();
}Particular attention : Because no objects are created , I didn't use it correctly , The date and other formats are converted into strings , Don't string , Otherwise, a listening error will be reported .
More rigorous usage , Listening classes can use generics , You don't have to create each .
Other more uses : Instructions · Language sparrow
ServletOutputStream fo=response.getOutputStream();
response.addHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setContentType("application/vnd.ms-excel;charset=utf-8");边栏推荐
- Message queuing - omnidirectional comparison
- Getting started with Python
- 06. talk about the difference and coding between -is and = = again
- MySQL-08
- Status mode, body can change at will
- SQL Server 函数
- 去哪儿网BI平台建设演进史
- numpy. frombuffer()
- Typora activation method
- Tencent's 2022 school recruitment of large factories started with salary, and the general contracting of cabbage is close to 40W!
猜你喜欢

Deeply uncover Ali (ant financial) technical interview process with preliminary preparation and learning direction

String类学习

How to design a good technical scheme

数据可视化实战:实验报告

canal部署、原理和使用介绍

小程序第三方微信授权登录的实现

On site commissioning - final method of kb4474419 for win7 x64 installation and vs2017 flash back

MySQL-09

去哪儿网BI平台建设演进史

Comparison between Prometheus and ZABBIX
随机推荐
数据治理工作的几种推进套路
Kolla ansible deploy openstack Yoga version
解决在win10下cmder无法使用find命令
Solve the problem that Cmdr cannot use find command under win10
Redis underlying data structure
302. 包含全部黑色像素的最小矩形 BFS
E-commerce seeks growth breakthrough with the help of small program technology
Redis底层数据结构
Getting to know concurrency problems
Day3 - variables and operators
PyTorch使用多GPU并行训练及其原理和注意事项
低代码实时数仓构建系统的设计与实践
类和对象的学习
EFK升级到ClickHouse的日志存储实战
EFK昇級到ClickHouse的日志存儲實戰
Underlying principle of MySQL index
数据可视化实战:数据可视化
Data visualization practice: Data Visualization
Definition of Halcon hand eye calibration
如何设计好的技术方案