当前位置:网站首页>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");
边栏推荐
猜你喜欢
Logstash——Logstash向Email发送告警邮件
解决在win10下cmder无法使用find命令
【群内问题学期汇总】初学者的部分参考问题
Younger sister Juan takes you to learn JDBC -- two days' Sprint Day2
Class and object learning
PyTorch使用多GPU并行训练及其原理和注意事项
Kolla ansible deploy openstack Yoga version
Handwritten background management framework template (I)
MySQL-08
Logstash——Logstash将数据推送至Redis
随机推荐
Data visualization practice: Data Visualization
如何设计好的技术方案
MySQL-07
MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications
Application of cow read / write replication mechanism in Linux, redis and file systems
家庭记账程序(第二版 加入了循环)
EFK升级到ClickHouse的日志存储实战
小程序如何关联微信小程序二维码,实现二码聚合
Force buckle 875 Coco, who likes bananas
302. minimum rectangular BFS with all black pixels
[intra group questions semester summary] some reference questions for beginners
Tortoise and rabbit race example
消息队列-消息事务管理对比
06. talk about the difference and coding between -is and = = again
SQL server functions
numpy. frombuffer()
Selective Search for Object Recognition 论文笔记【图片目标分割】
Efk Upgrade to clickhouse log Storage Reality
花生壳内网穿透映射NPM私服问题
Interface oriented programming