通用的excel导出功能需要做两部操作:
1、前端入参增加needExport=true
2、服务端Controller查询返回的Vo增加元注解@ExcelProperty(value = {"设施id"},index =1)
3、如果需要实现个性化的excel导出,自定义一个类继承AbstractDIYExport.java实现createExcel方法,默认使用的是DefaultDIYExport.java
一、前端入参增加needExport=true
{
"head": {
"channelCode": "1",
"cloudSessionId": "c86c1f48-bb20-0001-1894-ffd01c9f103c",
"transactionId": "c86c1f4d-ad50-0001-8467-1d3f86061a5f",
"cloudUserId": "c8645e6e-8400-0001-59a2-f690edad4d00"
},
"body": {
"isShowTreeTemplate": "1",
"needExport": true,
"draw": 1,
"length": 10,
"start": 1
}
}
二、服务端Controller查询返回的Vo增加继承BaseRowModel,导出的字段增加@ExcelProperty
Evt 增加成员变量boolean needExport
public class QueryFacilitiesPaginationEvtextends QueryPaginationEvt{
private boolean needExport;
public boolean isNeedExport() {
return needExport;
}
public void setNeedExport(boolean needExport) {
this.needExport = needExport;
}
}
public class FacilitiesVo extends BaseRowModel {
@ExcelProperty(value = {"设施id"},index =1)
@ApiModelProperty(value="设施id")
private String facilitiesId;
@ExcelProperty(value = {"租户企业id"},index =2)
@ApiModelProperty(value="租户企业id")
private String partnerId;
/**
* 设施id
*/
public StringgetFacilitiesId() {
return this.facilitiesId;
}
public void setFacilitiesId(String facilitiesId) {
this.facilitiesId = facilitiesId;
}
/**
* 租户企业id
*/
public StringgetPartnerId() {
return this.partnerId;
}
public void setPartnerId(String partnerId) {
this.partnerId = partnerId;
}
}
@ExcelProperty的使用可以参见:
https://github.com/alibaba/easyexcel/blob/master/src/test/java/com/alibaba/easyexcel/test/model/WriteModel.java
三、需要支持个性化的excel导出新增寄一个类继承AbstractDIYExport ,然后在Controller的查询方法上增加@CloudExport
@CloudExport(diyClass= DefaultDIYExport.class,headLineMun =1,sheetNo =1,startRow =1,maxRowNum =10000)
public @ResponseBody ResponseMessage>doQueryFacilitiesPagination(@RequestBody RequestMessage requestMessage){
CloudSession cloudSession =requestMessage.getBody().getCloudSession();
if(cloudSession==null){
return new ResponseMessage().retNotLogin();
}
return facilitiesService.queryFacilitiesPagination(requestMessage);
}
public class DefaultDIYExport extends AbstractDIYExport {
@Override
public void createExcel(CloudExport cloudExport, List list, OutputStream out)throws IOException {
if(CollectionUtils.isNotEmpty(list)){
//生成excel
ExcelWriter writer =null;
String templatePath = cloudExport.templatePath();
//excel 导出模板放classpath 下,如 demo.xlsx, cn/com/demo/demo.xlsx
InputStream inputStream =null;
if(StringUtils.isNotBlank(templatePath)){
inputStream = getResourcesFileInputStream(templatePath);
writer = EasyExcelFactory.getWriterWithTemp(inputStream,out, ExcelTypeEnum.XLSX,true);
}else{
writer = EasyExcelFactory.getWriter(out);
}
Class cls = list.get(0).getClass();
Sheet sheet =new Sheet(cloudExport.sheetNo(), cloudExport.headLineMun(),cls);
sheet.setStartRow(cloudExport.startRow());//从第几行开始
writer.write(list, sheet);
writer.finish();
if(inputStream !=null){
inputStream.close();
}
out.close();
}
}
}
详细使用说明参见:
https://github.com/alibaba/easyexcel/