2020-11-26 基于Hutool的Excel导出

效果

在这里插入图片描述


流程
  1. 设置列名
  2. 放入数据
  3. 设置一下response
  4. 回写

代码
  • 工具类
package cn.mb.excelexport.util;

import cn.hutool.poi.excel.ExcelWriter;
import cn.mb.excelexport.annotation.ExportField;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.List;

/**
 * <p>
 *  导出工具
 * </p>
 *
 * @author: guohaibin
 * @createDate: 2020/11/26
 */
public class ExportUtil {

    /**
     * <p>
     *  导出excel
     *  格式
     *              标题(会合并字段数的单元格)
     *      列名1     列名2     ...
     *      行1数据1  行2数据2   ...
     * </p>
     * @param cls           导出类
     * @param rows          导出数据
     * @param fileName      文件名(不含后缀)
     * @param title         标题(第一行必须有标题)
     * @param writer        hutool Excel工具,ExcelUtil.getWriter()为导出xls,ExcelUtil.getWriter(true)为导出xlsx
     * @param request       请求
     * @param response      响应
     * @return void
     * @author guohaibin
     * @date 2020-11-26 14:17:00
     */
    public static  <T> void exportExcel(Class<T> cls, List<T> rows, String fileName, String title, ExcelWriter writer,
                                        HttpServletRequest request, HttpServletResponse response) throws IOException {
        //  首行需合并多少单元格
        int totalColumn = 0;
        Field[] fields = cls.getDeclaredFields();
        //  配置列名
        for (Field field : fields) {
            ExportField annotation = field.getDeclaredAnnotation(ExportField.class);
            if (annotation == null) continue;
            writer.addHeaderAlias(field.getName(), annotation.desc());
            totalColumn++;
        }
        //  首行合并单元格
        writer.merge(totalColumn, title);
        //  写入数据
        writer.write(rows, true);
        //  设置文件名
        String suffix = writer.isXlsx() ? ".xlsx" : ".xls";
        fileName = fileName + suffix;
        //
        try {
            String agent = request.getHeader("USER-AGENT");
            if (null != agent && -1 != agent.indexOf("MSIE") || null != agent && -1 != agent.indexOf("Trident") || null != agent && -1 != agent.indexOf("Edge")) {// ie浏览器及Edge浏览器
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
                // 火狐,Chrome等浏览器
                fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.setContentType("application/ms-excel;charset=utf-8");
        OutputStream out = response.getOutputStream();
        writer.flush(out);
        writer.close();
        out.close();
    }

}

  • 注解
package cn.mb.excelexport.annotation;

import java.lang.annotation.*;

/**
 * <p>
 *  导出字段
 *      还可以添加是否导出该字段属性以及其他自定义属性来扩充功能
 * </p>
 *
 * @author: guohaibin
 * @createDate: 2020/11/26
 */
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExportField {

    /**
     * 描述
     */
    String desc();

}

  • jar
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!--hutool工具包-->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.5.1</version>
</dependency>
<!--poi-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

小结
上面工具类通过反射配置Excel的列名,且通过泛型来保证数据传递,其中通过注解方式
来标记字段(后续可在该注解上添加其他功能),使用者只需要传递所需数据,即可向前端
回写二进制流。
	get请求下载好实现,但post带参请求下载,在向前端返回二进制流后,不知道前端如何
处理,如果有知道的兄弟可以教学一波!!
	目前项目中就是通过url带token的方式来携带登录token,在拦截器中判断多了一层判断 

demo
学习
设置列宽
postman测试下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值