You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Spring Boot+React实现员工数据Excel报表生成并返回浏览器

实现Spring Boot生成Excel并返回给React前端

我来给你一步步拆解实现方案,分为后端Spring Boot处理和前端React请求下载两部分,亲测好用:

一、后端Spring Boot实现

1. 引入Excel处理依赖

推荐用阿里的EasyExcel(比Apache POI更轻量,能有效避免内存溢出问题),在pom.xml中添加依赖:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.3.2</version> <!-- 可替换为最新稳定版 -->
</dependency>

2. 创建员工实体类

对应你的数据库表字段,用@ExcelProperty注解指定Excel列名,方便映射:

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;

@Data
public class Employee {
    @ExcelProperty("员工ID")
    private Long id;
    
    @ExcelProperty("姓名")
    private String name;
    
    @ExcelProperty("部门")
    private String department;
    
    @ExcelProperty("入职日期")
    private String hireDate;
    
    // 其他字段根据你的数据库表结构补充
}

3. 编写Service层获取员工数据

假设你已经用MyBatis/JPA实现了数据访问,Service层负责从数据库查询员工列表:

import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class EmployeeService {
    private final EmployeeMapper employeeMapper; // 注入你的数据访问Mapper
    
    public EmployeeService(EmployeeMapper employeeMapper) {
        this.employeeMapper = employeeMapper;
    }
    
    public List<Employee> getAllEmployees() {
        // 这里替换成你的实际查询逻辑,比如MyBatis-Plus的selectList
        return employeeMapper.selectList(null);
    }
}

4. 编写导出Excel的Controller

核心是把Excel文件写入响应流,同时设置正确的响应头,让浏览器识别为下载文件:

import com.alibaba.excel.EasyExcel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
public class ExcelExportController {
    private final EmployeeService employeeService;
    
    public ExcelExportController(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    @GetMapping("/export/employees")
    public void exportEmployees(HttpServletResponse response) throws Exception {
        // 设置响应内容类型和编码
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 处理中文文件名乱码问题
        String fileName = URLEncoder.encode("员工列表", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        
        // 从数据库获取员工数据
        List<Employee> employeeList = employeeService.getAllEmployees();
        
        // 把数据写入响应流,生成Excel
        EasyExcel.write(response.getOutputStream(), Employee.class)
                .sheet("员工数据")
                .doWrite(employeeList);
    }
}

二、前端React实现下载

用axios发送请求,处理二进制Blob数据,生成下载链接触发浏览器下载:

1. 安装axios(如果未安装)

npm install axios

2. 编写导出按钮组件

在React组件中添加导出按钮,点击后发起请求并处理下载:

import axios from 'axios';
import { Button } from 'antd'; // 用你项目的UI组件,原生button也可

const EmployeeExport = () => {
    const handleExport = async () => {
        try {
            const response = await axios.get('/api/export/employees', {
                responseType: 'blob', // 必须指定响应类型为blob,否则会拿到乱码字符串
            });
            
            // 创建临时下载链接
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', '员工列表.xlsx'); // 设置下载文件名
            document.body.appendChild(link);
            link.click();
            
            // 清理临时资源
            window.URL.revokeObjectURL(url);
            document.body.removeChild(link);
        } catch (error) {
            console.error('导出失败:', error);
            alert('导出Excel失败,请稍后重试');
        }
    };

    return (
        <Button type="primary" onClick={handleExport}>
            导出员工列表
        </Button>
    );
};

export default EmployeeExport;

注意事项

  • 确保Spring Boot配置了跨域允许,避免前端请求被拦截;
  • 中文文件名一定要做编码处理,否则部分浏览器会显示乱码;
  • 如果数据量极大,EasyExcel支持分批次写入,可避免内存溢出;
  • 前端请求必须设置responseType: 'blob',否则无法正确解析二进制文件。

内容的提问来源于stack exchange,提问作者Manikanta B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:06:48