添加pom依赖
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.6</version>
</dependency><!--工具类-->
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.3.1</version>
</dependency>
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.21</version>
</dependency>
实体类
package com.example.mybatismysql8demo.vo;import lombok.*;
import lombok.experimental.Accessors;import java.math.BigDecimal;
import java.util.Date;@NoArgsConstructor
@AllArgsConstructor
@Data
@Accessors(chain = true)
public class EasyExcelExportVo {private String name;private Integer age;private Integer height;private BigDecimal weight;private Date birthday;}
执行方法
package com.example.mybatismysql8demo.controller;import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.example.mybatismysql8demo.vo.EasyExcelExportVo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;@Slf4j
@RestController
public class EasyExcelController {@RequestMapping(value = "easyExcelExport", method = RequestMethod.GET)public void easyExcelExport(HttpServletResponse response) {dynamic(response,2);}public void dynamic(HttpServletResponse response,Integer state){if (state == 1){//动态生成exceltry {//动态列值List<String> headName = Arrays.asList("姓名","性别","身高","年龄");List<List<String>> result = new ArrayList<>();headName.forEach(data-> result.add(Collections.singletonList(data)));//告诉浏览器数据格式,将头和数据传到前台response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("utf-8");response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("用户信息表.xls", StandardCharsets.UTF_8));EasyExcel.write(response.getOutputStream()).autoCloseStream(Boolean.FALSE).head(result).sheet("信息表").doWrite(Collections.EMPTY_LIST);//关闭流response.getOutputStream().close();} catch (IOException e) {e.printStackTrace();}}else {//动态导出exceltry {//动态列值Map<Integer,Object> map = getField();List<String> headName = (List<String>) map.get(1);List<List<String>> result = new ArrayList<>();headName.forEach(data->{//添加标题result.add(Lists.newArrayList("用户信息",data));});//数据List<List<Object>> data = (List<List<Object>>) map.get(2);//告诉浏览器数据格式,将头和数据传到前台response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("utf-8");response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("用户信息表.xls", StandardCharsets.UTF_8));EasyExcel.write(response.getOutputStream()).autoCloseStream(Boolean.FALSE).head(result).sheet("信息表").doWrite(data);//关闭流response.getOutputStream().close();} catch (IOException e) {e.printStackTrace();}}}public static Map<Integer,Object> getField(){//前端配置动态字段,存储数据库String fields = "[{\"field\":\"age\",\"text\":\"年龄\"},{\"field\":\"height\",\"text\":\"身高\"},{\"field\":\"name\",\"text\":\"姓名\"},{\"field\":\"weight\",\"text\":\"体重\"}]";List<Map> mapList = JSONObject.parseArray(fields,Map.class);//字段名称List<String> fieldList = mapList.stream().map(v -> v.get("text").toString()).collect(Collectors.toList());//字段属性名称List<String> fieldNames = mapList.stream().map(v -> v.get("field").toString()).collect(Collectors.toList());//获取数据List<EasyExcelExportVo> data = getDateList();//数据处理List<List<Object>> list = new ArrayList<>();data.forEach(value->{//将对象转换为mapMap<String, Object> mapInfo = BeanUtil.beanToMap(value);//遍历动态字段值List<Object> objectList = new ArrayList<>();fieldNames.forEach(key->{objectList.add(mapInfo.get(key));});list.add(objectList);});Map<Integer,Object> map = new HashMap<>(2);map.put(1,fieldList);map.put(2,list);return map;}public static void main(String[] args) {System.out.println(getField());}public static List<EasyExcelExportVo> getDateList(){List<EasyExcelExportVo> info = new ArrayList<>();Collections.addAll(info,new EasyExcelExportVo().setName("张三").setAge(18).setHeight(160).setWeight(new BigDecimal(100)).setBirthday(new Date()),new EasyExcelExportVo().setName("李四").setAge(18).setHeight(160).setWeight(new BigDecimal(100)).setBirthday(new Date()),new EasyExcelExportVo().setName("王五").setAge(18).setHeight(160).setWeight(new BigDecimal(100)).setBirthday(new Date()),new EasyExcelExportVo().setName("小明").setAge(20).setHeight(180).setWeight(new BigDecimal(120)).setBirthday(new Date()));return info;}}