当前位置:网站首页>Ali open source (easyexcel)
Ali open source (easyexcel)
2022-06-28 19:43:00 【Prodigal son Tang Shao】
Alibaba open source (EasyExcel)
1. Official website and introduction
1.GitHub Official website
GitHub Address :https://github.com/alibaba/easyexcel
Use document address https://alibaba-easyexcel.github.io/index.html
2. Introduce
EasyExcel Alibaba is an open source excel Processing framework , To make it easy to use 、 Famous for saving memory .Java Domain analysis 、 Generate Excel Well known frameworks are Apache poi、jxl etc. . But they all have a serious problem that is very memory consuming . If your system has a small amount of concurrency, it may be OK , But once concurrency comes up, it will OOM perhaps JVM Frequent full gc.easyExcel The main reason that can greatly reduce the memory occupation is parsing Excel The file data is not loaded into memory at one time , Instead, read data from a row on the disk , One by one .
2.easyexcel Use
1. stay pom.xml Add dependency in
<!-- easyexcel start -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.6</version>
</dependency>
<!-- easyexcel end -->
2.ExcelListener( Call... On import )
Use EasyExcel, You need to create a listening class and inherit AnalysisEventListener
public class CheliangListener extends AnalysisEventListener {
// This value can be obtained through an instance
private List<Object> datas = new ArrayList<Object>();
public void invoke(Object o, AnalysisContext analysisContext) {
datas.add(o);// Data stored in list, For batch processing , Or follow up their own business logic processing .
doSomething(o);// According to their own business to deal with
}
private void doSomething(Object object) {
//1、 Warehousing call interface
}
public List<Object> getDatas() {
return datas;
}
public void setDatas(List<Object> datas) {
this.datas = datas;
}
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
// datas.clear();// End of parsing destroy unused resources
}
}
PS: among , invoke() and doAfterAllAnalysed() Is a method that must be implemented .
stay invoke() in , We encapsulate the data into list in , In the controller , adopt getter() Method to get data , So we can get easyexcel Help us parse the data , Then type the data , such , We can write data .
3. Create entity class
This is an entity class . We export Excel when , Sometimes a header is required , If you need a header field , We can add... To the corresponding entity class @ExcelProperty(value = "id", index = 0) , @ExcelIgnore By default, all fields will be associated with excel To match , This annotation will ignore this field , And inheritance BaseRowModel. among value On behalf of exporting Excel when , The header name corresponding to this field ;index Represents the header position corresponding to the field .
public class BdCheliangEntity extends BaseRowModel implements Serializable {
/** Primary key */
@ExcelIgnore
private String id;
/** Creator name */
@ExcelIgnore
private String createName;
/** Creator login name */
@ExcelIgnore
private String createBy;
/** Date of creation */
@ExcelIgnore
private Date createDate;
/** Updated by */
@ExcelIgnore
private String updateName;
/** Updater login name */
@ExcelIgnore
private String updateBy;
/** Updated date */
@ExcelIgnore
private Date updateDate;
/** Department */
@ExcelIgnore
private String sysOrgCode;
/** Company */
@ExcelIgnore
private String sysCompanyCode;
/** Process status */
@ExcelIgnore
private String bpmStatus;
/** license plate number */
@ExcelProperty(value=" license plate number ",index=0)
private String chepaihao;
/** models */
@ExcelProperty(value=" models ",index=1)
private String chexing;
/** Maximum volume */
@ExcelProperty(value=" Maximum volume ",index=2)
private String zuidatiji;
/** load */
@ExcelProperty(value=" load ",index=3)
private String zaizhong;
/** Carrying capacity */
@ExcelProperty(value=" Carrying capacity ",index=4)
private String zairen;
/** Leave your driver's license */
@ExcelProperty(value=" Leave your driver's license ",index=5)
private String jiazhao;
/** Is it available */
@ExcelProperty(value=" Is it available ",index=6)
private String zhuangtai;
/** remarks */
@ExcelProperty(value=" remarks ",index=7)
private String beizhu;
/** Default driver */
@ExcelProperty(value=" Default driver ",index=8)
private String username;
/**gps*/
@ExcelProperty(value="gps",index=9)
private String gpsid;
@ExcelProperty(value=" Area ",index=10)
private String quyu;
// Query criteria
@ExcelIgnore
private Integer page = 1;
@ExcelIgnore
private Integer rows = 10;
@ExcelIgnore
private Integer pagerows;
@ExcelIgnore
private String searchKey;
@ExcelIgnore
private String searchKey2;
@ExcelIgnore
private String searchKey3;
4.easyexcel Use of export
controller layer
step :
- Add response header information ;
- add to ExcelWriter;
- add to Sheet( Forms );
- Add data ;
- Output .
// export
@ResponseBody
@RequestMapping("/exportExcel")
public String exporExcel(BdCheliangEntity bdCheliangEntity, HttpServletResponse response) throws IOException {
String result = null;
ExcelWriter writer = null;
OutputStream outputStream = response.getOutputStream();
try {
String fileName =" Vehicle information .xls";
// Add response header information
response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName,"UTF-8"));
response.setContentType("application/msexcel;charset=UTF-8");// Set type
response.setHeader("Pragma", "No-cache");// Set head
response.setHeader("Cache-Control", "no-cache");// Set head
response.setDateHeader("Expires", 0);// Set date header
// Instantiation ExcelWriter
writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLS, true);
// Instantiate the form
Sheet sheet = new Sheet(1, 0, BdCheliangEntity.class);
sheet.setSheetName(" Vehicle information ");
// get data
List<BdCheliangEntity> list = bdCheliangService.outExcel(bdCheliangEntity);
// Output
writer.write(list, sheet);
writer.finish();
outputStream.flush();
outputStream.close();
result = "success";
} catch (IOException e) {
e.printStackTrace();
result = "fail";
} finally {
try {
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
service layer
@Override
public List<BdCheliangEntity> outExcel(BdCheliangEntity bdCheliangEntity) {
List<BdCheliangEntity> list=bdCheliangMapper.outExcel(bdCheliangEntity);
return list;
}
dao layer
List<BdCheliangEntity> outExcel(BdCheliangEntity query);
5.easyexcel Use of import
controller layer
// Import
@RequestMapping("/importExcel")
@ResponseBody
public String importExcel(MultipartFile uploadFile) {
String result = null;
InputStream is = null;
try {
String filename = uploadFile.getOriginalFilename();
if (filename != null && (filename.toLowerCase().endsWith(".xls") || filename.toLowerCase().endsWith(".xlsx"))) {
is = new BufferedInputStream(uploadFile.getInputStream());
} else {
return " The imported file is not excel file ";
}
result = bdCheliangService.readExcel(is);
} catch (Exception e) {
e.printStackTrace();
return " System error ";
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
service layer
step :
- Instantiation ExcelListener;
- Instantiation ExcelReader;
- Read table information ;
- Insert data into the database
// Import
@Override
public String readExcel(InputStream is) {
IdWorker idWorker=new IdWorker(0,0);
ExcelReader excelReader = null;
CheliangListener listener = new CheliangListener();
// excelReader = new ExcelReader(is, ExcelTypeEnum.XLSX, null, listener);
excelReader = EasyExcelFactory.getReader(is, listener);
excelReader.read(new Sheet(1, 1, BdCheliangEntity.class));
List<Object> importList = listener.getDatas();
List<BdCheliangEntity> list = new ArrayList<>();
BdCheliangEntity info = new BdCheliangEntity();
// Convert data type , And insert it into the database
for (int i = 0; i < importList.size(); i++) {
info = (BdCheliangEntity) importList.get(i);
String id = String.valueOf(idWorker.nextId());
info.setId(id);
info.setCreateDate(new Date());
list.add(info);
}
if(list.size()>=1) {
bdCheliangMapper.importExcel(list);
list.clear();
}
return "success";
}
dao layer
void importExcel(List<BdCheliangEntity> list);
6. effect
export excel effect :
Front end interface effect :
Please check the source code for the specific code
3. Source code address
边栏推荐
- C语言-函数知识点
- Autumn recruitment experience sharing | how to prepare for bank interview
- Digital collection, ten thousand words long text, most of the questions you want to know have been clearly explained, which must be seen by practitioners
- 行业分析| 快对讲,楼宇对讲
- 论文3 VScode&texlive&SumatraPDF打造完美书写论文工具
- 2837. The total number of teams
- 国内有正规安全的外汇交易商吗?
- 从设计交付到开发,轻松畅快高效率!
- Group programming TIANTI competition exercise - continuously updating
- Bayesian inference problem, MCMC and variational inference
猜你喜欢

math_ Proving common equivalent infinitesimal & Case & substitution

R language GLM generalized linear model: logistic regression, Poisson regression fitting mouse clinical trial data (dose and response) examples and self-test questions

How does redis implement inventory deduction? How to prevent oversold?

智能计算系统2 bangc算子开发的demo (CPU和MLU270的异构编程流程)

On the first anniversary of the data security law, which four major changes are coming?

让企业数字化砸锅和IT主管背锅的软件供应链安全风险指南

阿里开源(EasyExcel)

大火的虚拟人在哪些产业开始发力?

Number theory -- detailed proof of Euler function, sieve method for Euler function, Euler theorem and Fermat theorem

Bayesian inference problem, MCMC and variational inference
随机推荐
Concours de segmentation des images gastro - intestinales de kaggle Baseline
SQL calculates daily new users and retention rate indicators
How does redis implement inventory deduction? How to prevent oversold?
Markdown drawing Mermaid practical tutorial
jsp中获取session中的值
Digital collection, ten thousand words long text, most of the questions you want to know have been clearly explained, which must be seen by practitioners
多测师肖sirapp中riginal error: Could not extract PIDs from ps output. PIDS: [], Procs: [“bad pid
列表加入计时器(正计时、倒计时)
return new int[]{i + 1, mid + 1}; return {i + 1, mid + 1};
Gaozelong, a digital economy expert: Yingke changed its name to yingcosmos. Will yuancosmos become the next growth engine of Yingke?
Bayesian inference problem, MCMC and variational inference
Installation and configuration of CGAL in PCL environment 5.4.1
Machine learning notes temperature+softmax
Number theory -- detailed proof of Euler function, sieve method for Euler function, Euler theorem and Fermat theorem
Fontawesome icon for color gradient
Variable autoencoders (vaes)
Bayesian inference problem, MCMC and variational inference
Upward and downward transformation
Parallax JS special effect JS carousel map plug-in
Can py SQL get the table structure?