1、引入EasyExcel依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.2</version>
</dependency>
2、定义ExcelModel表单模型
public class ExcelModel implements Serializable {
private String fileName;//定义导出文件名
private String[] headMap;//定义导出导出表头
private String[] fieldMap;//定义指导导出字段
private List<Map<String,Object>> datalist;//表单数据
}
3、定义ExcelUtils工具类
public static void dataWrite(@RequestBody ExcelModel excelModel,HttpServletResponse response){
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
try {
String fileName = URLEncoder.encode(excelModel.getFileName(),"UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream()).head(setHead(excelModel.getHeadMap())).sheet(excelModel.getFileName()).doWrite(setData(excelModel.getDatalist(),excelModel.getFieldMap()));
// 这里需要设置不关闭流
} catch (Exception e) {
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
throw new SunException("下载失败",e);
}
}
/**
* 设置表格表头
* @param headMap Stirng[] 指定需要导出的表头
* @return
*/
public static List<List<String>> setHead(String[] headMap){
List<List<String>> list = new ArrayList<List<String>>();
for (String head : headMap ){
List<String> h = new ArrayList<String>();
h.add(head);
list.add(h);
}
return list;
}
/**
* 设置表单数据
* @param datalist List<Map<String,Object>>格式、方便使用Map集合的数据处理
* @param fieldMap String[] 指定需要的导出字段的数组
* @return
*/
public static List<List<Object>> setData(List<Map<String,Object>> datalist,String[] fieldMap){
List<List<Object>> lists = new ArrayList<List<Object>>();
for(Map<String,Object> map : datalist){
List<Object> list = new ArrayList<Object>();
for (int i=0;i<fieldMap.length;i++){
list.add(map.get(fieldMap[i]));
}
lists.add(list);
}
return lists;
}
4、接口具体实现类
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog>
implements SysLogService{
@Override
public List<Map<String,Object>> queryAllLog(Map<String, Object> params) {
return baseMapper.selectMaps(new QueryWrapper<>());
}
}
5、控制类进行具体实现
@GetMapping("/export")
public void export(@RequestParam Map<String,Object> params){
HttpServletResponse res = HttpContextUtils.getHttpServletResponse();
List<Map<String,Object>> list = sysLogService.queryAllLog(params);
ExcelModel model = new ExcelModel();
model.setFileName("导出测试");
String[] headMap ={"用户名","操作方式"};//自定义表头
String[] dataMap ={"username","operation"};//自定义导出字符串
model.setHeadMap(headMap);
model.setFieldMap(dataMap);
model.setDatalist(list);
ExcelUtils.dataWrite(model,res);
}
标签:String,导出,EasyExcel,List,表头,public,SpringBoot3,new,response
From: https://www.cnblogs.com/appdesign/p/18332361