Excel文件生成与下载(SpringBoot项目)(easypoi)

news/2024/7/21 3:43:13 标签: excel, spring boot, 后端

说明

通过接口,导出表格。

使用SpringBoot框架和easypoi表格解析框架,生成Excel表格,并通过接口下载。

表格示例

在这里插入图片描述

依赖

版本

<easypoi.version>4.4.0</easypoi.version>

依赖

<!-- easypoi -->
<dependency>
        <groupId>cn.afterturn</groupId>
        <artifactId>easypoi-base</artifactId>
        <version>${easypoi.version}</version>
</dependency>
<dependency>
        <groupId>cn.afterturn</groupId>
        <artifactId>easypoi-web</artifactId>
        <version>${easypoi.version}</version>
</dependency>
<dependency>
        <groupId>cn.afterturn</groupId>
        <artifactId>easypoi-annotation</artifactId>
        <version>${easypoi.version}</version>
</dependency>

代码

Controller

package com.example.service;

import com.example.service.UserExcelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.io.IOException;

@RestController
@RequestMapping("file")
@Api(tags = "文件")
public class FileController {

    @Autowired
    private UserExcelService userExcelService;


    @GetMapping("export/user_excel")
    @ApiOperation("导出用户列表(Excel表格,以附件形式下载)")
    public void exportUserExcel(HttpServletResponse response) throws IOException {
        userExcelService.downloadUserExcel(response);
    }

}

Service

package com.example.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.example.data.excel.UserExcel;
import com.example.db.entity.UserEntity;
import com.example.util.FileUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class UserExcelService {


    public void downloadUserExcel(HttpServletResponse response) throws IOException {
        // 获取用户表格对象列表
        List<UserExcel> userExcelList = listUserExcel();
        // 获取表格下载的输出流
        OutputStream outputStream = FileUtil.getExcelOutputStream("用户列表.xlsx", response);
        // 导出表格
        ExcelExportUtil.exportExcel(new ExportParams("用户列表(抬头)", "sheet"), UserExcel.class, userExcelList).write(outputStream);
    }


    /**
     * 获取用户表格对象列表
     */
    private List<UserExcel> listUserExcel() {
        List<UserEntity> userEntities = listUserEntity();

        // 将查询出来的 数据库Entity,转换为 Excel实体 。
        return userEntities.stream().map(item -> {
            UserExcel vo = new UserExcel();
            BeanUtils.copyProperties(item, vo);
            return vo;
        }).collect(Collectors.toList());
    }


    /**
     * 模拟从数据库查询出数据列表。
     */
    private List<UserEntity> listUserEntity() {
        UserEntity user1 = new UserEntity();
        user1.setId("1");
        user1.setName("张三");
        user1.setAccount("zhangsan");
        user1.setPassword("123456");
        user1.setAge(25);
        user1.setEmail("zhangsan@example.com");
        user1.setStatus(1);
        user1.setRemark("VIP客户");

        UserEntity user2 = new UserEntity();
        user2.setId("2");
        user2.setName("李四");
        user2.setAccount("lisi");
        user2.setPassword("111222");
        user2.setAge(28);
        user2.setEmail("lisi@example.com");
        user2.setStatus(2);
        user2.setRemark("客户已禁用");

        return Stream.of(user1, user2).collect(Collectors.toList());
    }


}

表格实体

package com.example.data.excel;

import cn.afterturn.easypoi.excel.annotation.Excel;
import io.swagger.annotations.ApiModel;
import lombok.Data;

/**
 * 用户信息-Excel对象;
 *
 * @author : songguanxun
 * @date : 2023-9-8
 */
@Data
@ApiModel(value = "用户-Excel对象")
public class UserExcel {

    @Excel(name = "姓名", orderNum = "1", width = 30)
    private String name;

    @Excel(name = "账号", orderNum = "2", width = 30)
    private String account;

    @Excel(name = "年龄", orderNum = "3", width = 20)
    private Integer age;

    @Excel(name = "电子邮箱", orderNum = "4", width = 30)
    private String email;

    @Excel(name = "账号状态", orderNum = "5", replace = {"启用_1", "禁用_2"}, width = 20)
    private Integer status;

    @Excel(name = "备注", orderNum = "6", width = 50)
    private String remark;

}

数据库实体

package com.example.db.entity;

import lombok.Data;

/**
 * 用户
 *
 * @author : songguanxun
 * @date : 2023-9-8
 */
@Data
public class UserEntity {

    private String id;

    private String name;

    private String account;

    private String password;

    private Integer age;

    private String email;

    private Integer status;

    private String remark;

}

文件工具类

package com.example.util;

import com.example.enumeration.ContentDispositionEnum;
import org.springframework.http.HttpHeaders;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * 文件工具类
 */
public class FileUtil {

    /**
     * 获取表格下载的输出流
     *
     * @param fileName 文件名
     * @param response 接口响应对象
     * @return 输出流
     */
    public static OutputStream getExcelOutputStream(String fileName, HttpServletResponse response) throws IOException {
        String fileNameEncoded = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, ContentDispositionEnum.ATTACHMENT.getCode() + ";fileName=" + fileNameEncoded);
        return response.getOutputStream();
    }

}


http://www.niftyadmin.cn/n/5012331.html

相关文章

部署zookeeper集群

zookeeper和jdk下载地址 jdk 链接&#xff1a;https://pan.baidu.com/s/13GpNaAiHM5HSDJ66ebBtEg 提取码&#xff1a;90se zookeeper 链接&#xff1a;https://pan.baidu.com/s/1nSFKEhSGNiwgSPZWdb7hkw 提取码&#xff1a;u5l2 在所有的机器上面执行下面步骤&#xff1a; 1.上…

计算机竞赛 基于深度学习的植物识别算法 - cnn opencv python

文章目录 0 前言1 课题背景2 具体实现3 数据收集和处理3 MobileNetV2网络4 损失函数softmax 交叉熵4.1 softmax函数4.2 交叉熵损失函数 5 优化器SGD6 最后 0 前言 &#x1f525; 优质竞赛项目系列&#xff0c;今天要分享的是 &#x1f6a9; **基于深度学习的植物识别算法 ** …

JS遍历对象的七种方法

一、for...in let obj { name:"cheng", sex:man} Object.defineProperty(obj,age,{value:"18",enumerable:true }) for(item in obj){console.log(item) } 1.Object.defineProperty&#xff0c;使用enumerable:true&#xff0c;才能被枚举&#xff0c;默…

Qt配置使用MSVC编译器

Qt配置使用MSVC编译器_qt msvc-CSDN博客注意:Qt支持的MSVC就是2017和2015&#xff0c;所以vs也要下载2017&#xff0c;不要直接用最新的&#xff0c;安装路径都用默认的。程序运行失败时可以尝试windeployqt拷贝库文件到本地&#xff0c;然后有可能就能运行了。VS官网下载Visua…

一个线程的生命周期有哪几种状态?它们之间如何流转的?

一个线程的生命周期可以分为以下几种状态: New(新建):当线程对象被创建但尚未启动时,它处于新建状态。在这个阶段,线程对象被实例化,但还没有调用它的start()方法。 Runnable(可运行):一旦线程被启动,它就处于可运行状态。在这个状态下,线程可能正在执行,也可能正…

LeetCode 2651. Calculate Delayed Arrival Time 简单

本文属于「征服LeetCode」系列文章之一&#xff0c;这一系列正式开始于2021/08/12。由于LeetCode上部分题目有锁&#xff0c;本系列将至少持续到刷完所有无锁题之日为止&#xff1b;由于LeetCode还在不断地创建新题&#xff0c;本系列的终止日期可能是永远。在这一系列刷题文章…

国家网络安全周2023时间是什么时候?有什么特点?谁举办的?

国家网络安全周2023时间是什么时候&#xff1f; 2023年国家网络安全宣传周将于9月11日至17日在全国范围内统一开展。其中开幕式等重要活动将在福建省福州市举行。今年网安周期间&#xff0c;除开幕式外&#xff0c;还将举行网络安全博览会、网络安全技术高峰论坛、网络安全微视…

centos7 firewalld ip转发设置、安装docker-compose出现错误、docker-compose部署Yapi

一 centos7 firewalld ip转发设置 #!/bin/bash #开启系统路由模式功能 vim /etc/sysctl.conf #添加下面一行 net.ipv4.ip_forward1 #运行这个命令会输出上面添加的那一行信息&#xff0c;意思是使内核修改生效 sysctl -p #开启firewalld systemctl start firewalld #防火墙开启…