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

本文介绍了一种利用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);
    }

/**
     * 将数据转成file文件
     *
     * @throws IOException
     */
    public static File getExcelBigFile(List<Map<String, Object>> sheetsList, String fileName) throws IOException {
        Workbook workbook = ExcelExportUtil.exportExcel(sheetsList, ExcelType.XSSF);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        LocalDateTime localDateTime = Instant.ofEpochMilli(System.currentTimeMillis()).atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
        String excelFileName = fileName + df.format(localDateTime) + ".xls";
        File file = new File(excelFileName);
        if (workbook != null) {
            FileOutputStream outputStream = new FileOutputStream(excelFileName);
            workbook.write(outputStream);
        }
        return file;
    }

    /**
     * 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);
        //或者使用下面的方法,能实现多个sheets导出
		List<Map<String, Object>> sheetsList = new ArrayList<>();
                for (StoreInfo storeInfo : storeInfoList) {
                    List<AppStoreGoods> list = appStoreGoodsService.list(Wrappers.<AppStoreGoods>lambdaQuery().eq(AppStoreGoods::getStoreId, storeInfo.getId()));
                    Map<String, Object> docMap = new HashMap<>();
                    ExportParams docParams = new ExportParams();
                    docParams.setSheetName(storeInfo.getStoreName());
                    docParams.setType(ExcelType.XSSF);//该处应该与ExcelExportUtil.exportExcel方法中的一致,不然会出现转换错误
                    docMap.put("title", docParams);
                    docMap.put("entity", AppStoreGoods.class);
                    docMap.put("data", list);
                    sheetsList.add(docMap);
                }
     	File fileTemp = ExcelUtil.getExcelBigFile(sheetsList, username + "门店商品数据");
    }

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

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

ExcelUtil.exportExcel(exportList,"长城用户信息","1-3号洞", Export.class,"长城用户信息",response); 
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

XuDream

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

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

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

打赏作者

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

抵扣说明:

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

余额充值