当前位置:网站首页>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");
边栏推荐
- MySQL-07
- Logstash -- send an alert message to the nail using the throttle filter
- The use of loops in SQL syntax
- On site commissioning - final method of kb4474419 for win7 x64 installation and vs2017 flash back
- Gram 矩阵
- Consul service registration and discovery
- Factory method pattern, abstract factory pattern
- Class and object learning
- 数据可视化实战:实验报告
- 【群内问题学期汇总】初学者的部分参考问题
猜你喜欢
Test depends on abstraction and does not depend on concrete
Tencent's 2022 school recruitment of large factories started with salary, and the general contracting of cabbage is close to 40W!
Status mode, body can change at will
Consul service registration and discovery
Kolla ansible deploy openstack Yoga version
E-commerce seeks growth breakthrough with the help of small program technology
重载和重写
工厂方法模式、抽象工厂模式
MySQL-08
Pytorch (network model)
随机推荐
05. basic data type - Dict
原型模式,咩咩乱叫
消息队列-功能、性能、运维对比
MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications
【 langage c】 stockage des données d'analyse approfondie en mémoire
SQL Server view
Vs2022 offline installation package download and activation
Factory method pattern, abstract factory pattern
Keepalived to achieve high service availability
去哪儿网BI平台建设演进史
Tencent's 2022 school recruitment of large factories started with salary, and the general contracting of cabbage is close to 40W!
Multi thread synchronous downloading of network pictures
Definition of Halcon hand eye calibration
Redis底层数据结构
Logstash - logstash sends an alarm email to email
Logstash——Logstash向Email发送告警邮件
Adapter mode
实时数仓方案如何选型和构建
SQL Server视图
MySQL-08