当前位置:网站首页>Easyexcel complex header export (one to many)
Easyexcel complex header export (one to many)
2022-07-28 15:36:00 【m0_ sixty-seven million four hundred and one thousand six hundr】
Preface
Before , Yes EasyExcel Complex header import ( One to many ) The blog of , The result is right , Many netizens left messages asking me to write another imported . difficult to refuse such kindness , Just wrote a , Found a lot of problems .
About EasyPoi Framework issues , No more details here , Refer to my other blog , The address is as follows :
EasyExcel Complex header import ( One to many )_ The blog of -CSDN Blog _easyexcel Complex header
actually , There are no detailed export tutorials in official documents or online , You need to refer to the official to realize . I only succeeded in making one and a half barrels of water for a long time , I'm very ashamed , Record here , Convenient back .
explain :EasyExcel Unable to deal with List It's nested inside List The situation of , The scheme I adopted is realized by merging tables .
below , First, give the specific implementation , Then talk about the problem .
EasyExcel Implementation of one to many export
Entity object
/**
* Customer information export class , Indicate the export template style, etc . Is real and EasyPoi Interactive classes
*/
@Data
@EqualsAndHashCode
@HeadRowHeight(30)
@ContentRowHeight(20)
@ColumnWidth(20)
@HeadStyle(fillForegroundColor = 44)
@NoArgsConstructor
class Customer extends BaseRowModel implements Serializable {
@ExcelProperty({" Customer number "})
private String userCode;
@ExcelProperty({" Customer name "})
private String userName;
@ColumnWidth(25)
@ExcelProperty({" Customer address "})
private String address;
@ExcelProperty({" Contact information ", " Contact name "})
private String personName;
@ExcelProperty({" Contact information ", " contact number "})
private String telephone;
public Customer(CustomerInfo customerInfo) {
this.userCode = customerInfo.getUserCode();
this.userName = customerInfo.getUserName();
this.address = customerInfo.getAddress();
this.personName = customerInfo.getPersonList().get(0).getPersonName();
this.telephone = customerInfo.getPersonList().get(0).getTelephone();
}
public Customer(CustomerInfo.Person person) {
this.personName = person.getPersonName();
this.telephone = person.getTelephone();
}
}
/**
* Basic customer information , Analogy program from service Information obtained by the layer
* actually ,EasyPoi Can only read simple String、boolean、integer、float byte[] And so on . Unable to deal with List、Map And so on .
* At present , You can also define only type converters Converter, See the reference link at the end of the article for details .
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
class CustomerInfo {
private String userCode;
private String userName;
private String address;
private List<Person> personList;
@Data
@AllArgsConstructor
@NoArgsConstructor
static class Person {
private String personName;
private String telephone;
}
}
Controller layer
@IgnoreUserToken
@GetMapping("/exportExcel")
@ApiOperation(" export Excel")
public void exportExcel(HttpServletResponse response) throws Exception {
// Get export data , Simulation from service Get the floor list data .
List<CustomerInfo> list = getData();
// Get all customer information , The largest number of contacts . And take this quantity as the basis for line consolidation
int maxColNum = 1;
for (CustomerInfo ele : list) {
if (ele.getPersonList().size() > maxColNum) {
maxColNum = ele.getPersonList().size();
}
}
// Arrangement , speak List contain List Data format , Change to List The format of
final int finalMaxColNum = maxColNum;
List<Customer> result = list.stream()
.flatMap(ele -> {
List<Customer> temp = new ArrayList<>();
// Get the number of current customer contacts
int len = ele.getPersonList().size();
// First add a complete customer information
temp.add(new Customer(ele));
for (int i = 1; i < finalMaxColNum; i++) {
if (i >= len) {
// To reach maxColNum Of , repair null placeholder .
temp.add(new Customer());
} else {
// Only add contact information
temp.add(new Customer(ele.getPersonList().get(i)));
}
}
return temp.stream();
}).collect(Collectors.toList());
// Set up excel Header style
WriteSheet sheet = EasyExcel.writerSheet(" Customer information ").head(Customer.class).sheetNo(1).build();
// Set up excel Table style
ExcelWriter writer = EasyExcel.write(response.getOutputStream()).needHead(true).excelType(ExcelTypeEnum.XLSX)
.registerWriteHandler(new LoopMergeStrategy(maxColNum, 0)) // Set the first column every maxColNum merger
.registerWriteHandler(new LoopMergeStrategy(maxColNum, 1)) // Set the second column every maxColNum merger
.registerWriteHandler(new LoopMergeStrategy(maxColNum, 2)) // Set the third column every maxColNum merger
.build();
// write in excel data
writer.write(result, sheet);
// Notify the browser to download and process in the form of attachment , When setting the return header, note that the file name has Chinese
response.setHeader("Content-disposition", "attachment;filename=" + new String(" Customer information list ".getBytes("gb2312"), "ISO8859-1") + ".xlsx");
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
writer.finish();
}
getDate Method ( Used to simulate service Data obtained by layer )
public static List<CustomerInfo> getData() {
List<CustomerInfo> data = new ArrayList<>();
CustomerInfo customer = new CustomerInfo();
customer.setUserCode("CT_jx001");
customer.setUserName(" Jiangxi Telecom Company ");
customer.setAddress(" Qingshanhu District, Nanchang City, Jiangxi Province ");
CustomerInfo.Person person1 = new CustomerInfo.Person(" Zhang San ", "12345678910");
CustomerInfo.Person person2 = new CustomerInfo.Person(" Li Si ", "10987654321");
List<CustomerInfo.Person> personList = new ArrayList<>();
personList.add(person1);
personList.add(person2);
customer.setPersonList(personList);
data.add(customer);
CustomerInfo customer2 = new CustomerInfo();
customer2.setUserCode("CT_jx002");
customer2.setUserName(" Guangdong Telecom Company ");
customer2.setAddress(" Huadu District, Guangzhou City, Guangdong Province ");
CustomerInfo.Person person12 = new CustomerInfo.Person(" Xiao Ming ", "12345678910");
CustomerInfo.Person person22 = new CustomerInfo.Person(" Xiaohong ", "10987654321");
CustomerInfo.Person person23 = new CustomerInfo.Person(" Xiao Wang ", "12345678910");
List<CustomerInfo.Person> personList2 = new ArrayList<>();
personList2.add(person12);
personList2.add(person22);
personList2.add(person23);
customer2.setPersonList(personList2);
data.add(customer2);
return data;
}
effect
Interface is get Type of , Browser direct access , Download the file , The effect is as follows .


By the way debug effect , Easy to understand .
debug effect


Problems and Prospects
The problem of this method can be seen from the implementation effect , There will be blank lines .
however , This empty line cannot be avoided , Because multiple rows merge , Only according to the maximum value , And it cannot be dynamically adjusted .
This way, , Although it can realize the export of complex headers , But the display is not satisfactory , Mainly because of the problem of empty lines .
I really can't find a better solution , Only the following ideas are provided here .
You can also pass EasyPoi Of Custom interceptors 、 Data format converter 、 Template write 、 merge cell 、 Write repeatedly And so on .

Reference link
In addition to the official website address , Refer to the following article .
Can not find ‘Converter‘ support class List Problem solving _ I took this nickname and it was never used ? The blog of -CSDN Blog question description com.alibaba.excel.exception.ExcelDataConvertException: Can not find ‘Converter’ support class List. Problem explanation EasyExcel In the open source framework Converter Interface convertToExcelData Only the conversion BigDecimal、Bolean、Byte[]、btye[]、Byte、Date、Double、File、Float、InputStream、Integer、Long、Short、URL these [ Here is the picture 006]https://blog.csdn.net/qq_41049371/article/details/120156305EasyExcel ExcelDataConvertException:Can not find ‘Converter‘ support class ArrayList Problem solving _ Xudong monster's blog -CSDN Blog question description :com.alibaba.excel.exception.ExcelDataConvertException:Cannotfind’Converter’supportclassArrayList. Problem analysis :1、 see doWrite(List data) Source code found when Converter Interface convertToExcelData Only the conversion BigDecimal、Bolean、Byte[]、btye[]、Byte、Date、Double、File、Float、InputStream、…[ Here is the picture 007]https://blog.csdn.net/qq_38974638/article/details/116609844
边栏推荐
- subst命令将一个文件夹镜像成本地的一个磁盘
- 3、基本常数和宏定义
- Summary of common redis commands (self provided)
- Heuristic merging simple problem on tree
- Write a standard character device driver with your hands
- Introduction to grpc
- 4.8 HD-GR GNSS导航软件源码
- Solve the problem of pycharm using PowerShell
- 10. Implementation of related data accumulation task
- 文件及目录操作(5)
猜你喜欢

Idea debugging burpsuit plug-in

Grpc protocol buffer

Endnote 与word关联

Voltage relay dy-28c

堆操作

Easy start, swagger

Customer service system attached to crmeb Standard Edition

Sharing of award-winning activities: you can get up to iphone13 after using WordPress to build your own blog
![[jspwiki]jspwiki installation deployment and configuration](/img/3c/81a201bb80dcbb17d1c97b1a5bb215.png)
[jspwiki]jspwiki installation deployment and configuration

Problems encountered by pyppeter
随机推荐
How many of the top ten test tools in 2022 do you master
Principle and configuration of MPLS LDP
Crmeb Standard Version window+phpstudy8 installation tutorial (I)
百度提出动态自蒸馏方法,结合交互模型与双塔模型实现稠密段落检索
Endnote 与word关联
Problems encountered by pyppeter
22、电文处理任务实现
flowable工作流所有业务概念
使用Mock技术帮助提升测试效率的小tips,你知道几个?
详解.NET的求复杂类型集合的差集、交集、并集
Encapsulate the unified return object messageresult
Svg verification code recognition experience
9. Related data accumulation task definition
ECCV 2022 | SSP: 自支持匹配的小样本任务新思想
堆操作
VS使用技巧
How many tips do you know about using mock technology to help improve test efficiency?
Leetcode - number of operations, non repeating numbers, diagonal traversal, Joseph Ring
Opencv - cut out mask foreground area from grayscale image
php parse_ URL bypass whitelist