当前位置:网站首页>Import / export function implementation
Import / export function implementation
2022-06-26 06:09: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");边栏推荐
- COW读写复制机制在Linux,Redis ,文件系统中的应用
- tf.nn.top_k()
- 机器学习 07:PCA 及其 sklearn 源码解读
- numpy.log
- Yamaha robot splits visual strings
- Consul service registration and discovery
- Test depends on abstraction and does not depend on concrete
- numpy. frombuffer()
- 421-二叉树(226. 翻转二叉树、101. 对称二叉树、104.二叉树的最大深度、222.完全二叉树的节点个数)
- Mongodb——使用Mongodb对字段中字符串内容进行截取,并进行分组统计
猜你喜欢

电商借助小程序技术发力寻找增长突破口

MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications

Pytorch (environment, tensorboard, transforms, torchvision, dataloader)

MySQL database-01 database overview

家庭记账程序(第二版 加入了循环)

事务与消息语义

Adapter mode

Household accounting procedures (the second edition includes a cycle)
![Selective search for object recognition paper notes [image object segmentation]](/img/cf/d3b08d41083f37c164b26a96b989c9.png)
Selective search for object recognition paper notes [image object segmentation]

原型模式,咩咩乱叫
随机推荐
Gram 矩阵
SQL Server view
MySQL-06
Day4 branch and loop
数据可视化实战:数据可视化
Basic construction of SSM framework
Logstash——Logstash向Email发送告警邮件
"= =" difference from "equals"
Mongodb -- use mongodb to intercept the string content in the field and perform grouping statistics
Redis底层数据结构
numpy. exp()
Implement the runnable interface
SQL Server 函数
5分钟包你学会正则表达式
Upgrading technology to art
tf. nn. top_ k()
[intra group questions semester summary] some reference questions for beginners
canal部署、原理和使用介绍
Sql查询时间段内容
MySQL-08