springboot整合easypoi实现浏览器自动下载excel文件,一行代码实现,附带完整项目和导出工具。(一)

先看效果图:
在这里插入图片描述
备注:

  1. 此方法不能实现自定义表头导出,只能导出实体类中所有的属性
  2. 此种方法封装了easypoi的方法
  3. 如果需要自定义表头,需要使用easypoi原理实现。详情请点击springboot整合easypoi实现浏览器自动下载自定义表头excel文件,,附带导出工具。
  4. 完整项目下载项目地址(温馨提示,一下代码基本上展示95%)

可能出现的问题:

java.lang.NoClassDefFoundError:org/apache/poi/xssf/streaming/SXSSFWorkbook

这样是因为jar的问题,因为jar会进行覆盖,所以按照下面导入jar不会出现这种问题。

实现过程
4. 引入依赖

<!--excel导出工具-->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.poi</groupId>
                    <artifactId>poi-ooxml</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.poi</groupId>
                    <artifactId>poi</artifactId>
                </exclusion>
            </exclusions>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.1</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.1</version>
        </dependency>

5. 工具类

/**
 * Excel导入导出工具类
 * @author lenovo
 */

public class ExcelUtil {

    /**
     * excel 导出
     *
     * @param list     数据列表
     * @param fileName 导出时的excel名称
     * @param response
     */
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
        defaultExport(list, fileName, response);
    }

    /**
     * 默认的 excel 导出
     *
     * @param list     数据列表
     * @param fileName 导出时的excel名称
     * @param response
     */
    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
        //把数据添加到excel表格中
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        downLoadExcel(fileName, response, workbook);
    }

    /**
     * excel 导出
     *
     * @param list         数据列表
     * @param pojoClass    pojo类型
     * @param fileName     导出时的excel名称
     * @param response
     * @param exportParams 导出参数(标题、sheet名称、是否创建表头,表格类型)
     */
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException {
        //把数据添加到excel表格中
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downLoadExcel(fileName, response, workbook);
    }

    /**
     * excel 导出
     *
     * @param list         数据列表
     * @param pojoClass    pojo类型
     * @param fileName     导出时的excel名称
     * @param exportParams 导出参数(标题、sheet名称、是否创建表头,表格类型)
     * @param response
     */
    public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams, HttpServletResponse response) throws IOException {
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    /**
     * excel 导出
     *
     * @param list      数据列表
     * @param title     表格内数据标题
     * @param sheetName sheet名称
     * @param pojoClass pojo类型
     * @param fileName  导出时的excel名称
     * @param response
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) throws IOException {
        ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        defaultExport(list, pojoClass, fileName, response,exportParams);
    }


    /**
     * excel 导出
     *
     * @param list           数据列表
     * @param title          表格内数据标题
     * @param sheetName      sheet名称
     * @param pojoClass      pojo类型
     * @param fileName       导出时的excel名称
     * @param isCreateHeader 是否创建表头
     * @param response
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) throws IOException {
        ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }


    /**
     * excel下载
     *
     * @param fileName 下载时的文件名称
     * @param response
     * @param workbook excel数据
     */
    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }
}

6. 实体类
@ExcelTarget(“Export”) 千万不能忘记
@Excel(name = “时间”, width = 30)

package com.excel.entity;

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
import lombok.Data;

import java.io.Serializable;

/**
 * @author lenovo
 */
@Data
@ExcelTarget("Export")
public class Export implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * 时间
     */
    @Excel(name = "时间",  width = 30)
    private String datetime;
    /**
     * 姓名
     */
    @Excel(name = "姓名",  width = 30)
    private String name;
    /**
     * 年龄
     */
    @Excel(name = "年龄",  width = 30)
    private String age;
    /**
     * 性别
     */
    @Excel(name = "性别",  width = 30)
    private String gender;
    /**
     * 地址
     */
    @Excel(name = "地址",  width = 30)
    private String address;
}

7. 接口

@GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        //为了达到数据展示,手动写一些数据,实际情况可以去数据库获取
        List<Export> exportList=new ArrayList<>();
        for (int i=1;i<4;i++){
            Export export = new Export();
            export.setDatetime(DateUtil.now());
            export.setName("张三"+i+"号");
            export.setAge("张三"+i+"岁");
            export.setGender("男");
            export.setAddress("万里长城"+i+"号洞口");
            exportList.add(export);
        }
        //参数1:数据(数组)、参数2:报表标题、参数3:页面名、参数4:映射实体、参数5:文件名称、参数6:响应
        ExcelUtil.exportExcel(exportList,"长城用户信息","1-3号洞", Export.class,"长城用户信息",response);
    }

8. 浏览器访问该接口会直接下载excel,实现上述效果图。

9. 总结
只有这一行代码就可以实现excle导出。

ExcelUtil.exportExcel(exportList,"长城用户信息","1-3号洞", Export.class,"长城用户信息",response); 
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
首先,你需要在你的Spring Boot项目中添加Easypoi的依赖。可以在pom.xml中添加以下代码: ```xml <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>4.2.0</version> </dependency> ``` 接下来,你需要定义一个实体类作为导出的数据模型,并使用注解来定义每个字段的名称和格式。例如: ```java public class User { @Excel(name = "编号", orderNum = "0") private Integer id; @Excel(name = "用户名", orderNum = "1") private String username; @Excel(name = "注册时间", orderNum = "2", format = "yyyy-MM-dd HH:mm:ss") private Date createTime; // 省略getter和setter方法 } ``` 在上面的代码中,我们使用了@Excel注解来定义导出字段的名称、顺序和格式。其中,name属性指定了字段的名称,orderNum属性指定了字段在Excel文件中的顺序,format属性指定了时间字段的格式。 接下来,你可以在控制器中定义一个导出Excel文件的方法。例如: ```java @GetMapping("/export") public void export(HttpServletResponse response) throws IOException { List<User> userList = userService.getUserList(); // 定义导出Excel文件名称 String fileName = "用户列表.xlsx"; // 定义导出的数据表格 ExportParams exportParams = new ExportParams("用户列表", "用户信息"); // 创建Excel文件并写入数据 Workbook workbook = ExcelExportUtil.exportExcel(exportParams, User.class, userList); // 设置响应头 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); response.setContentType("application/vnd.ms-excel;charset=UTF-8"); // 将Excel文件写入响应输出流中 workbook.write(response.getOutputStream()); } ``` 在上面的代码中,我们使用了Easypoi提供的ExcelExportUtil工具类来创建导出Excel文件。其中,ExportParams对象用于定义导出文件的标题和表头,User.class用于定义数据模型,userList是要导出的数据集合。 最后,我们将Excel文件写入响应输出流中,以实现文件下载。 注意:如果你的时间字段是字符串类型,可以在导出时先将其转换为Date类型,然后再使用@Excel注解定义格式。例如: ```java public class User { @Excel(name = "编号", orderNum = "0") private Integer id; @Excel(name = "用户名", orderNum = "1") private String username; @Excel(name = "注册时间", orderNum = "2", format = "yyyy-MM-dd HH:mm:ss") private Date createTime; // 定义createTime的getter方法 public Date getCreateTime() { try { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(this.createTime); } catch (ParseException e) { e.printStackTrace(); return null; } } // 定义createTime的setter方法 public void setCreateTime(String createTime) { this.createTime = createTime; } } ``` 在上面的代码中,我们将createTime字段从字符串类型转换为Date类型,并在getter方法中返回Date类型的值。这样,就可以使用@Excel注解定义时间格式了。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XuDream

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值