current position:Home>Springboot implements excel import and export, which is easy to use, and poi can be thrown away
Springboot implements excel import and export, which is easy to use, and poi can be thrown away
2022-01-27 01:40:46 【m0_ sixty-four million eight hundred and sixty-seven thousand e】
@ApiOperation(value = “ Export member list Excel”)
@RequestMapping(value = “/exportMemberList”, method = RequestMethod.GET)
public void exportMemberList(ModelMap map,
HttpServletRequest request,
HttpServletResponse response) {
List memberList = LocalJsonUtil.getListFromJson(“json/members.json”, Member.class);
ExportParams params = new ExportParams(“ Membership list ”, “ Membership list ”, ExcelType.XSSF);
map.put(NormalExcelConstants.DATA_LIST, memberList);
map.put(NormalExcelConstants.CLASS, Member.class);
map.put(NormalExcelConstants.PARAMS, params);
map.put(NormalExcelConstants.FILE_NAME, “memberList”);
PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
}
}
- LocalJsonUtil Tool class , Can be directly from resources Get... In the directory JSON Data and convert to objects , For example, the members.json;
- Run the project , Directly through Swagger Access interface , Pay attention to Swagger The provider in cannot download directly , You need to click the download button in the return result , Access address :http://localhost:8088/swagger-ui/
- When the download is complete , Look at the file , A standard Excel The file has been exported .
Simple import
====
The import function is also very simple to implement , Let's take the import of member information list as an example .
- stay Controller Add an interface for importing Member Information , Here we need to pay attention to the use of @RequestPart Comments modify file upload parameters , Otherwise, in the Swagger You can't display the upload button in ;
/**
-
EasyPoi Import and export tests Controller
-
Created by macro on 2021/10/12.
*/
@Controller
@Api(tags = "EasyPoiControll
《 A big factory Java Analysis of interview questions + Back end development learning notes + The latest architecture explanation video + Practical project source code handout 》
【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 Full content open source sharing
er", description = “EasyPoi Import and export tests ”)
@RequestMapping("/easyPoi")
public class EasyPoiController {
@ApiOperation(“ from Excel Import member list ”)
@RequestMapping(value = “/importMemberList”, method = RequestMethod.POST)
@ResponseBody
public CommonResult importMemberList(@RequestPart(“file”) MultipartFile file) {
ImportParams params = new ImportParams();
params.setTitleRows(1);
params.setHeadRows(1);
try {
List list = ExcelImportUtil.importExcel(
file.getInputStream(),
Member.class, params);
return CommonResult.success(list);
} catch (Exception e) {
e.printStackTrace();
return CommonResult.failed(“ Import failed !”);
}
}
}
- And then in Swagger Middle test interface , Select the previously exported Excel File can , After successful import, the parsed data will be returned .
Complex Export
====
Of course EasyPoi You can also implement more complex Excel operation , For example, export an order list nested with member information and product information , Now let's realize !
- First add the item object Product, Used to encapsulate product information ;
/**
-
goods
-
Created by macro on 2021/10/12.
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class Product {
@Excel(name = “ID”, width = 10)
private Long id;
@Excel(name = “ goods SN”, width = 20)
private String productSn;
@Excel(name = “ Name of commodity ”, width = 20)
private String name;
@Excel(name = “ Product subtitle ”, width = 30)
private String subTitle;
@Excel(name = “ The brand name ”, width = 20)
private String brandName;
@Excel(name = “ commodity price ”, width = 10)
private BigDecimal price;
@Excel(name = “ Purchase quantity ”, width = 10, suffix = “ Pieces of ”)
private Integer count;
}
- Then add the order object Order, Orders and members are one-to-one , Use @ExcelEntity The note indicates , Orders and goods are a one to many relationship , Use @ExcelCollection The note indicates ,Order This is the nested order data we need to export ;
/**
-
Order
-
Created by macro on 2021/10/12.
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class Order {
@Excel(name = “ID”, width = 10,needMerge = true)
private Long id;
@Excel(name = “ The order number ”, width = 20,needMerge = true)
private String orderSn;
@Excel(name = “ Creation time ”, width = 20, format = “yyyy-MM-dd HH:mm:ss”,needMerge = true)
private Date createTime;
@Excel(name = “ Shipping address ”, width = 20,needMerge = true )
private String receiverAddress;
@ExcelEntity(name = “ Member information ”)
private Member member;
@ExcelCollection(name = “ List of goods ”)
private List productList;
}
- The next in Controller Add an interface to export the order list , Because of some member information, we don't need to export , You can call ExportParams Medium setExclusions Methods eliminate ;
/**
-
EasyPoi Import and export tests Controller
-
Created by macro on 2021/10/12.
*/
@Controller
@Api(tags = “EasyPoiController”, description = “EasyPoi Import and export tests ”)
@RequestMapping("/easyPoi")
public class EasyPoiController {
@ApiOperation(value = “ Export order list Excel”)
@RequestMapping(value = “/exportOrderList”, method = RequestMethod.GET)
public void exportOrderList(ModelMap map,
HttpServletRequest request,
HttpServletResponse response) {
List orderList = getOrderList();
ExportParams params = new ExportParams(“ Order list ”, “ Order list ”, ExcelType.XSSF);
// Exclude some fields when exporting
params.setExclusions(new String[]{“ID”, “ Date of birth ”, “ Gender ”});
map.put(NormalExcelConstants.DATA_LIST, orderList);
map.put(NormalExcelConstants.CLASS, Order.class);
map.put(NormalExcelConstants.PARAMS, params);
map.put(NormalExcelConstants.FILE_NAME, “orderList”);
PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
}
}
- stay Swagger Access interface test in , Export order list Excel;
- When the download is complete , Look at the file ,EasyPoi Export complex Excel It's also very simple !
Custom processing
=====
If you want to do some custom processing on the exported fields ,EasyPoi Also supportive , For example, in the member information , If the user does not set a nickname , We added the information that has not been set yet .
- We need to add a processor to inherit the default ExcelDataHandlerDefaultImpl class , And then in exportHandler Method ;
/**
-
Custom field handling
-
Created by macro on 2021/10/13.
*/
public class MemberExcelDataHandler extends ExcelDataHandlerDefaultImpl {
@Override
public Object exportHandler(Member obj, String name, Object value) {
if(“ nickname ”.equals(name)){
String emptyValue = “ Not set yet ”;
if(value==null){
return super.exportHandler(obj,name,emptyValue);
}
if(value instanceof String&&StrUtil.isBlank((String) value)){
return super.exportHandler(obj,name,emptyValue);
}
}
return super.exportHandler(obj, name, value);
}
@Override
public Object importHandler(Member obj, String name, Object value) {
return super.importHandler(obj, name, value);
}
}
- And then modify Controller The interface , call MemberExcelDataHandler The processor setNeedHandlerFields Set the fields that need custom processing , And call ExportParams Of setDataHandler Set custom processor ;
/**
-
EasyPoi Import and export tests Controller
-
Created by macro on 2021/10/12.
*/
@Controller
@Api(tags = “EasyPoiController”, description = “EasyPoi Import and export tests ”)
@RequestMapping("/easyPoi")
public class EasyPoiController {
@ApiOperation(value = “ Export member list Excel”)
@RequestMapping(value = “/exportMemberList”, method = RequestMethod.GET)
public void exportMemberList(ModelMap map,
HttpServletRequest request,
HttpServletResponse response) {
List memberList = LocalJsonUtil.getListFromJson(“json/members.json”, Member.class);
ExportParams params = new ExportParams(“ Membership list ”, “ Membership list ”, ExcelType.XSSF);
// Customize the export results
MemberExcelDataHandler handler = new MemberExcelDataHandler();
copyright notice
author[m0_ sixty-four million eight hundred and sixty-seven thousand e],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270140443615.html
The sidebar is recommended
- Spring IOC container loading process
- [thinking] the difference between singleton mode and static method - object-oriented programming
- Hadoop environment setup (MySQL environment configuration)
- 10 minutes, using node JS creates a real-time early warning system for bad weather!
- Git tool
- Force deduction algorithm - 92 Reverse linked list II
- What is the sub problem of dynamic programming?
- C / C + +: static keyword summary
- Idea does not have the artifacts option when configuring Tomcat
- I don't know how to start this
guess what you like
-
Matlab simulation of transportation optimization algorithm based on PSO
-
MySQL slow log optimization
-
[Vue] as the window is stretched (larger, smaller, wider and higher), the text will not be displayed
-
Popular Linux distributions for embedded computing
-
The 72 year old uncle became popular. Wu Jing and Guo fan made his story into a film, which made countless dreamers blush
-
How to save computer research
-
The final examination subjects of a class are mathematical programming, and the scores are sorted and output from high to low
-
Two pronged approach, Tsinghua Professor Pro code JDK and hotspot source code notes, one-time learning to understand
-
C + + recursive knapsack problem
-
The use of GIT and GitHub and the latest git tutorial are easy to understand -- Video notes of crazy God speaking
Random recommended
- Ignition database test
- Context didn't understand why he got a high salary?, Nginxfair principle
- Bootstrap switch switch control user's guide, springcloud actual combat video
- A list that contains only strings. What other search methods can be used except sequential search
- [matlab path planning] multi ant colony algorithm grid map path planning [including GUI source code 650]
- [matlab path planning] improved genetic algorithm grid map path planning [including source code phase 525]
- Iinternet network path management system
- Appium settings app is not running after 5000ms
- Reactnative foundation - 07 (background image, status bar, statusbar)
- Reactnative foundation - 04 (custom rpx)
- Linux checks where the software is installed and what files are installed
- SQL statement fuzzy query and time interval filtering
- 69. Sqrt (x) (c + + problem solving version with vs runnable source program)
- Java project: OA management system (java + SSM + bootstrap + MySQL + JSP)
- Titanic passenger survival prediction
- Configuration and use of private image warehouse of microservice architect docker
- Relearn JavaScript events
- How does Java dynamically obtain what type of data is passed? It is used to judge whether the data is the same, dynamic data type
- How does the database cow optimize SQL?
- [data structure] chain structure of binary tree (pre order traversal) (middle order traversal) (post order traversal) (sequence traversal)
- Detailed explanation of red and black trees
- redhat7. 9 install database 19C
- Blue Bridge Cup notes: (the given elements are not repeated) complete arrangement (arrangement cannot be repeated, arrangement can be repeated)
- Detailed explanation of k8s management tool kubectl
- Android system view memory command