1.pom依赖(4.1.2)
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.3.0</version>
</dependency>
2.使用枚举暂存表头和属性
@Getter
@AllArgsConstrucotor
public enum ExportUserEnum{
USER_NAME(“username”,“用户名”),
AGE(“age”,“年龄”);
private string fieldName;
private string titleName;
//获取所用的字段名
public static List<String> getAllFieldName(){
Return Array.stream(ExportUserEnum.values()).map(ExportUserEnum::getFieldName).collect(Collectors.toList()));
}
//获取所用的表格列名(表头名)
public static List<String> getAllTitleName(){
Return Array.stream(ExportUserEnum.values()).map(ExportUserEnum::getTitleName).collect(Collectors.toList()));
}
}
3.将列表中的数据list存入到List<Map>中
List<User> users=userService.list(wrapper);
//属性
List<String>
allFidldNames=ExportUserEnum.getAllFieldName();
//表头
List<String> allTitleNames=ExportUserEnum.getAllTitleName();
List<map> list=new AraayList<>();
users.foreach(user->list.add(BeanUtil.beanToMap(user)));
//文件名
String excelName=”用户管理列表”+LocalDateTime.now();
4.使用poi中的工具类
ExcelUtil.exportExcel(list,fieldNameList,titleNameList,response,excelName);