基于EasyExcel实现的动态表头工具类

  1. 工具类
java 复制代码
package net.lesscoding.utils;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.google.common.collect.Lists;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author eleven
 * @date 2024/1/10 16:35
 * @apiNote
 */
public class DynamicHeaderUtil<T> {

    private static void setResponseHeader(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Connection", "close");
        response.setHeader("Content-Type", "application/octet-stream");
    }

    private static  <T> List<List<Object>> dataList(List<T> list, String... fields) {
        return list.stream()
                .map(entity -> Arrays.stream(fields)
                        .map(field -> Optional.ofNullable(BeanUtil.beanToMap(entity).get(field)).orElse(""))
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());
    }

    private static List<List<String>> dynamicHeader(String[] head) {
        return Arrays.stream(head)
                .map(item -> Lists.newArrayList(item.split(",")))
                .collect(Collectors.toList());
    }

    public static <T> void exportExcel(HttpServletResponse response, List<T> list, String fileName, String[] headerArray, String[] fields) throws Exception {
        setResponseHeader(response, fileName);
        try (ServletOutputStream outputStream = response.getOutputStream()){
            EasyExcel.write(outputStream)
                    // 这里放入动态头
                    .head(dynamicHeader(headerArray))
                    .sheet("模板")
                    .doWrite(dataList(list, fields));
        }

    }
}
  1. 使用
java 复制代码
package net.lesscoding.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.lesscoding.entity.Account;
import net.lesscoding.mapper.AccountMapper;
import net.lesscoding.utils.DynamicHeaderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author eleven
 * @date 2024/1/10 16:34
 * @apiNote
 */
@RestController
@RequestMapping("/test")
@SaIgnore
public class TestController {
    @Autowired
    private AccountMapper accountMapper;


    @GetMapping("/download")
    public void download(HttpServletResponse response) throws Exception {
        List<Account> accounts = accountMapper.selectList(new QueryWrapper<Account>()
                .last("limit 10"));
        DynamicHeaderUtil.exportExcel(response,
                accounts,
                "test",
                new String[]{
                        "个人信息,网络信息,省份",
                        "个人信息,网络信息,IP",
                        "个人信息,昵称",
                        "个人信息,账号",
                        "个人信息,Mac",
                },
                new String[]{"region", "nickname", "account", "mac"});
    }
}
相关推荐
李慕婉学姐44 分钟前
【开题答辩过程】以《基于JAVA的校园即时配送系统的设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
java·开发语言·数据库
奋进的芋圆2 小时前
Java 延时任务实现方案详解(适用于 Spring Boot 3)
java·spring boot·redis·rabbitmq
sxlishaobin3 小时前
设计模式之桥接模式
java·设计模式·桥接模式
model20053 小时前
alibaba linux3 系统盘网站迁移数据盘
java·服务器·前端
荒诞硬汉3 小时前
JavaBean相关补充
java·开发语言
提笔忘字的帝国3 小时前
【教程】macOS 如何完全卸载 Java 开发环境
java·开发语言·macos
2501_941882484 小时前
从灰度发布到流量切分的互联网工程语法控制与多语言实现实践思路随笔分享
java·开发语言
華勳全栈4 小时前
两天开发完成智能体平台
java·spring·go
alonewolf_994 小时前
Spring MVC重点功能底层源码深度解析
java·spring·mvc
沛沛老爹4 小时前
Java泛型擦除:原理、实践与应对策略
java·开发语言·人工智能·企业开发·发展趋势·技术原理