EasyExcel是一个非常方便的工具
例如:当然从代码你可以看到我默认是1w条为一页的,并且使用Function去执行对应的方法,其中只要去执行你对应的获取数据总数方法getTotal返回总数,以及分页获取数据的getList(会传入分页参数)方法返回list即可完成,批量数据分页导出。
实际是通过build.write()方法持续的往对应的Sheet中去不间断的写入,确实很强大!!!
public static void common(String sheetName, Class clazz, HttpServletResponse response, Function getTotal, Function getList){
ServletOutputStream os = null;
try {
os = response.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
ExcelWriter build = EasyExcel.write(os, clazz).build();
try {
String filename = encodingFilename(sheetName);
response.reset();
FileUtils.setAttachmentResponseHeader(response, filename);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
// 获取总数
int pageListTotal = (int) getTotal.apply(null);
int pageSize = 10000;
// 余数
int remainder = pageListTotal % pageSize;
// 商
int quotient = pageListTotal / pageSize;
// 一共请求次数
int number = remainder == 0 ? quotient : quotient + 1;
// 循环请求
for (int i = 1; i <= number; i++) {
PageQuery pageQuery = new PageQuery();
pageQuery.setPageNum(i);
pageQuery.setPageSize(pageSize);
Collection<?> list = (Collection<?>) getList.apply(pageQuery);
// 循环写
build.write(list, EasyExcel.writerSheet(0)
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
.registerConverter(new ExcelBigNumberConvert())
.head(clazz)
.build());
}
} catch (IOException e) {
throw new RuntimeException("导出Excel异常");
} finally {
build.finish();
}
}
使用:当然因为这里都是通用的方法,我都是使用的反射去调用方法的。
sheetName:导出的文件名称
clazz:对应的导出类
response:response
hyServiceCommon:对应的service对象(当然我这里是抽象父类)
obj:查询的参数对象
name:分页查询list的方法名称
totalName: 获取总数方法的名称
TableDataInfo: 通用分页返回对象,通过getRows()获取对应当前分页的list
public static <T> void exportExcelAll(String sheetName, Class<T> clazz, HttpServletResponse response, Object hyServiceCommon, Object obj,String name,String totalName) {
common(sheetName,clazz,response,
i->{
Object invokeTotal = HyReflectUtils.invoke(hyServiceCommon, totalName, obj);
return (int) invokeTotal;
},
page->{
Object invokelist = HyReflectUtils.invoke(hyServiceCommon, name, obj, page);
TableDataInfo<T> tableDataInfo = (TableDataInfo<T>) invokelist;
return tableDataInfo.getRows();
});
}
对应使用,当然你这里要是统一的继承了父类在父类统一有请求分页的方法和请求总数的方法,或许会更方便!
HyExcelUtil.exportExcelAll("xxx列表", xxxVo.class, response, xxxService, map, "getVoPageListNoTotal", "getTotalNum");
感谢: