SpringBoot实现导出复杂对象到Excel文件

2025-03-05 17:50

本文主要是介绍SpringBoot实现导出复杂对象到Excel文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《SpringBoot实现导出复杂对象到Excel文件》这篇文章主要为大家详细介绍了如何使用Hutool和EasyExcel两种方式来实现在SpringBoot项目中导出复杂对象到Excel文件,需要...

在Spring Boot项目中导出复杂对象到Excel文件,可以利用Hutool或EasyExcel等库来简化操作。这里我们将详细介绍如何使用Hutool和EasyExcel两种方式来实现这一功能。

使用Hutool导出复杂对象到Excel

首先确保你的pom.XML中添加了Hutool的依赖:

<depeandroidndency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutoChina编程ol-all</artifactId>
    <version>5.8.10</version> <!-- 请根据实际情况选择最新版本 -->
</dependency>

接下来是一个简单的示例,展示如何导出一个包含复杂对象的列表到Excel文件。

示例代码

假设我们有一个User类,它包含一个嵌套的Address对象。

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import Javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class UserController {

    @GetMapping("/exportUsers")
    public void exportUsers(HttpServletResponse response) throws IOException {
        // 模拟获取用户数据
        List<User> users = http://www.chinasem.cngetUsers();

        // 创建ExcelWriter实例
        ExcelWriter writer = ExcelUtil.getWriter(true); // true表示自动创建表头

        // 将复杂对象转换为Map列表,方便写入Excel
        List<Map<String, Object>> dataList = users.stream().map(user -> {
            Map<String, Object> row = new HashMap<>();
            row.put("ID", user.getId());
            row.put("姓名", user.getName());
            row.put("邮箱", user.getEmail());
            row.put("年龄", user.getAge());
            row.put("城市", user.getAddress().getCity());
            row.put("街道", user.getAddress().getStreet());
            return row;
        }).collect(Collectors.toList());

        // 写入数据
        writer.write(dataList, true);

        // 设置响应内容类型和头部信息
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        String fileName = URLEncoder.encode("用户列表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        // 将输出流写入response
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    private List<User> getUsers() {
        List<User> users = new ArrayList<>();
        Address address = new Address("北京", "中关村大街");
        users.add(new User(1L, "张三", "zhangsan@example.com", 28, address));
        return users;
    }
}

class User {
    private Long id;
    private String name;
    private String email;
    private Integer age;
    private Address address;

    public User(Long id, String name, String email, Integer age, Address address) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.age = age;
        this.address = address;
    }

    // getter和setter方法
}

编程China编程class Address {
    private String city;
    private String street;

    public Address(String city, String street) {
        this.city = city;
        this.street = street;
    }

    // getter和setter方法
}

使用EasyExcel导出复杂对象到Excel

EasyExcel是阿里巴巴开源的一个非常高效的Excel处理库,特别适合处理大数据量的Excel文件。首先,在pom.xml中添加EasyExcel的依赖:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.2.10</version> <!-- 请根据实际情况选择最新版本 -->
</dependency>

接下来是一个使用EasyExcel导出复杂对象的例子。

示例代码

假设我们仍然使用上面提到的UserAddress类。

import com.alibaba.excel.EasyExcel;
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;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api")
public class EasyExcelController {

    @GetMapping("/exportUsers")
    public void exportUsers(HttpServletResponse response) throws IOException {
        // 模拟获取用户数据
        List<User> users = getUsers();

        // 设置响应内容类型和头部信息
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        String fileName = URLEncoder.encode("用户列表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        // 使用EasyExcel写出数据到输出流
        EasyExcel.write(response.getOutputStream(), UserData.class)
                .sheet("用户信息")
                .doWrite(users);
    }

    private List<User> getUsers() {
        List<User> users = new ArrayList<>();
        Address address = new Address("北京", "中关村大街");
        users.add(new User(1L, "张三", "zhangsan@example.com", 28, address));
        return users;
    }
}

// 数据实体类
class UserData {
    @com.alibaba.excel.annotation.ExcelProperty("ID")
    private Long id;

    @com.alibaba.excel.annotation.ExcelProperty("姓名")
    private String name;

    @com.alibaba.excel.annotation.ExcelProperty("邮箱")
    private String email;

    @com.alibaba.excel.annotation.ExcelProperty("年龄")
    private Integer age;

    @com.alibaba.excel.annotation.ExcelProperty("城市")
    private String city;

    @com.alibaba.excel.annotation.ExcelProperty("街道")
    private String street;

    // 构造函数、getter和setter方法
    public UserData(User user) {
        this.id = user.getId();
        this.name = user.getName();
        this.email = user.getEmail();
        this.age = user.getAge();
        this.city = user.getAddress().getCity();
        this.street = user.getAddress().getStreet();
    }

    // getter和setter方法
}

在这个例子中,我们定义了一个UserData类来映射User对象的数据,并使用EasyExcel将这些数据写入Excel文件。

通过上述方法,你可以轻松地在Spring Boot项目中导出复杂对象到Excel文件。无论是使用Hutool还是EasyExcel,都可以有效地简化Excel处理的工作。

以上就是SpringBoot实现导出复android杂对象到Excel文件的详细内容,更多关于SpringBoot导出复杂对象到Excel的资料请关注China编程(www.chinasem.cn)其它相关文章!

这篇关于SpringBoot实现导出复杂对象到Excel文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1153647

相关文章

Spring Security常见问题及解决方案

《SpringSecurity常见问题及解决方案》SpringSecurity是Spring生态的安全框架,提供认证、授权及攻击防护,支持JWT、OAuth2集成,适用于保护Spring应用,需配置... 目录Spring Security 简介Spring Security 核心概念1. ​Securit

Python实现终端清屏的几种方式详解

《Python实现终端清屏的几种方式详解》在使用Python进行终端交互式编程时,我们经常需要清空当前终端屏幕的内容,本文为大家整理了几种常见的实现方法,有需要的小伙伴可以参考下... 目录方法一:使用 `os` 模块调用系统命令方法二:使用 `subprocess` 模块执行命令方法三:打印多个换行符模拟

SpringBoot+EasyPOI轻松实现Excel和Word导出PDF

《SpringBoot+EasyPOI轻松实现Excel和Word导出PDF》在企业级开发中,将Excel和Word文档导出为PDF是常见需求,本文将结合​​EasyPOI和​​Aspose系列工具实... 目录一、环境准备与依赖配置1.1 方案选型1.2 依赖配置(商业库方案)二、Excel 导出 PDF

Python实现MQTT通信的示例代码

《Python实现MQTT通信的示例代码》本文主要介绍了Python实现MQTT通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 安装paho-mqtt库‌2. 搭建MQTT代理服务器(Broker)‌‌3. pytho

SpringBoot改造MCP服务器的详细说明(StreamableHTTP 类型)

《SpringBoot改造MCP服务器的详细说明(StreamableHTTP类型)》本文介绍了SpringBoot如何实现MCPStreamableHTTP服务器,并且使用CherryStudio... 目录SpringBoot改造MCP服务器(StreamableHTTP)1 项目说明2 使用说明2.1

spring中的@MapperScan注解属性解析

《spring中的@MapperScan注解属性解析》@MapperScan是Spring集成MyBatis时自动扫描Mapper接口的注解,简化配置并支持多数据源,通过属性控制扫描路径和过滤条件,利... 目录一、核心功能与作用二、注解属性解析三、底层实现原理四、使用场景与最佳实践五、注意事项与常见问题六

Spring的RedisTemplate的json反序列泛型丢失问题解决

《Spring的RedisTemplate的json反序列泛型丢失问题解决》本文主要介绍了SpringRedisTemplate中使用JSON序列化时泛型信息丢失的问题及其提出三种解决方案,可以根据性... 目录背景解决方案方案一方案二方案三总结背景在使用RedisTemplate操作redis时我们针对

Java中Arrays类和Collections类常用方法示例详解

《Java中Arrays类和Collections类常用方法示例详解》本文总结了Java中Arrays和Collections类的常用方法,涵盖数组填充、排序、搜索、复制、列表转换等操作,帮助开发者高... 目录Arrays.fill()相关用法Arrays.toString()Arrays.sort()A

Spring Boot Maven 插件如何构建可执行 JAR 的核心配置

《SpringBootMaven插件如何构建可执行JAR的核心配置》SpringBoot核心Maven插件,用于生成可执行JAR/WAR,内置服务器简化部署,支持热部署、多环境配置及依赖管理... 目录前言一、插件的核心功能与目标1.1 插件的定位1.2 插件的 Goals(目标)1.3 插件定位1.4 核

如何使用Lombok进行spring 注入

《如何使用Lombok进行spring注入》本文介绍如何用Lombok简化Spring注入,推荐优先使用setter注入,通过注解自动生成getter/setter及构造器,减少冗余代码,提升开发效... Lombok为了开发环境简化代码,好处不用多说。spring 注入方式为2种,构造器注入和setter