项目中用到了easyExcel导出,返回的数据是List<Map<String, Object>> 格式,写个工具类大家使用吧,list<实体> 转List<Map<String, Object>>的工具类也挺多,map方便扩充一些要返给前端的字段
引入maven
<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.7</version>
</dependency>
工具类
/**
* web浏览器写 自动列宽
* 导出图片只支持单张,需要导出就在listkey的图片字段拼接showImg
* @param response
* @param fileName 文件名称
* @param headArray 文件头
* @param listKey list key
* @param dataList 数据list
*/
public static void download(HttpServletResponse response, String fileName, String[] headArray, String[] listKey, List<Map<String, Object>> dataList) {
try {
EasyExcel.write(EasyExcelUtils.outputStream(response, fileName)).head(EasyExcelUtils.head(headArray))
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet()
.doWrite(EasyExcelUtils.dataList(dataList, listKey));
} catch (IOException e) {
e.printStackTrace();
throw new RRException("导出失败");
}
}
public static List<List<String>> head(String[] array) {
List<List<String>> list = new ArrayList<>();
for (String s : array) {
List<String> head = new ArrayList<>();
head.add(s);
list.add(head);
}
return list;
}
public static List<List<Object>> dataList(List<Map<String, Object>> list, String[] listKey) throws MalformedURLException {
List<List<Object>> dataList = new ArrayList<List<Object>>();
for (Map<String, Object> map : list) {
List<Object> data = new ArrayList<Object>();
for (String s : listKey) {
if (map.get(s) == null) {
data.add("");
} else {
//数据格式处理 发现包含showImg字段就展示网络图片(简单的判断)
//也可以根据自己的需求进行格式化操作都放在这里
Object obj = map.get(s);
if(s.contains("showImg") && obj.toString().contains("http")){
data.add(new URL(obj.toString()));
}else {
data.add(obj.toString());
}
}
}
dataList.add(data);
}
return dataList;
}
public static OutputStream outputStream(HttpServletResponse response, String fileName) throws IOException {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
//防止中文乱码
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
return response.getOutputStream();
}
简单的写
public void variableTitleWrite() {
//查询出的数据
List<Map<String, Object>> list = this.selectMaps(ew);
String[] titleNames = {"姓名", "年龄", "性别"};
String[] listKeys = {"name", "age", "sex"};
//路径
String fileName = "1.xlsx";
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
EasyExcel.write(fileName).head(EasyExcelUtils.head(titleNames)).sheet("第一页").doWrite(EasyExcelUtils.dataList(list,listKeys));
}
WEB导出
@GetMapping("download")
public void download(HttpServletResponse response) throws IOException {
//查询出的数据
List<Map<String, Object>> list = this.selectMaps(ew);
String[] titleNames = {"姓名", "年龄", "性别","封面图"};
//在图片的字段后面加上showImg,不然出来的是图片链接
String[] listKeys = {"name", "age", "sex","covershowImg"};
EasyExcelUtils.download(response,"用户信息",headArray,listKey,list);
}
图片也导出来了