在springboot项目中,如何进行excel表格的导入导出功能?

news2025/7/15 18:52:12

以下是使用 Apache POI 和 EasyExcel 实现 Excel 表格导入导出功能的具体代码示例。

1. 使用 Apache POI 实现 Excel 导入导出

添加依赖

pom.xml 中添加 Apache POI 的依赖:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.3</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.3</version>
</dependency>
实体类
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;

    // 构造方法、getter 和 setter 方法
    public User() {}

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

    // getter 和 setter 方法省略
}
导出 Excel
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

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

public class ExcelUtil {

    public static void exportUserList(HttpServletResponse response, List<User> userList) {
        // 创建工作簿
        Workbook workbook = new HSSFWorkbook(); // 导出 .xls 文件,使用 XSSFWorkbook 导出 .xlsx 文件
        // 创建工作表
        Sheet sheet = workbook.createSheet("用户信息表");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        String[] headers = {"ID", "姓名", "年龄", "邮箱"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 填充数据
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            Row dataRow = sheet.createRow(i + 1);
            dataRow.createCell(0).setCellValue(user.getId() == null ? "" : user.getId().toString());
            dataRow.createCell(1).setCellValue(user.getName() == null ? "" : user.getName());
            dataRow.createCell(2).setCellValue(user.getAge() == null ? "" : user.getAge().toString());
            dataRow.createCell(3).setCellValue(user.getEmail() == null ? "" : user.getEmail());
        }

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        String fileName = "用户信息表.xls"; // 文件名
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
导入 Excel
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ExcelImportUtil {

    public static List<User> importUserList(MultipartFile file) {
        List<User> userList = new ArrayList<>();

        try {
            // 获取文件流
            InputStream inputStream = file.getInputStream();
            // 创建工作簿
            Workbook workbook = WorkbookFactory.create(inputStream);
            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);

            // 遍历行
            for (int i = 1; i <= sheet.getLastRowNum(); i++) { // 从第 2 行(索引 1)开始读取数据
                Row row = sheet.getRow(i);
                if (row == null) continue;

                // 获取单元格数据
                Long id = getCellValue(row.getCell(0));
                String name = getCellValue(row.getCell(1));
                Integer age = getCellValue(row.getCell(2));
                String email = getCellValue(row.getCell(3));

                // 创建 User 对象并添加到列表
                User user = new User(id, name, age, email);
                userList.add(user);
            }

            workbook.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return userList;
    }

    private static Long getCellValue(Cell cell) {
        if (cell == null) return null;
        if (cell.getCellType() == CellType.NUMERIC) {
            return (long) cell.getNumericCellValue();
        } else if (cell.getCellType() == CellType.STRING) {
            return Long.parseLong(cell.getStringCellValue());
        }
        return null;
    }

    private static String getCellValue(Cell cell) {
        if (cell == null) return null;
        if (cell.getCellType() == CellType.NUMERIC) {
            return String.valueOf((long) cell.getNumericCellValue());
        } else if (cell.getCellType() == CellType.STRING) {
            return cell.getStringCellValue();
        }
        return null;
    }
}

2. 使用 EasyExcel 实现 Excel 导入导出

添加依赖

pom.xml 中添加 EasyExcel 的依赖:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.2.0</version>
</dependency>
实体类
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.format.NumberFormat;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;

import java.util.Date;

public class PersonVO {

    @ExcelProperty(value = "姓名", index = 0)
    private String name;

    @ExcelProperty(value = "年龄", index = 1)
    @ColumnWidth(15)
    @NumberFormat("#")
    private Integer age;

    @ExcelProperty(value = "出生日期", index = 2)
    @DateTimeFormat("yyyy-MM-dd")
    private Date birthday;

    // getter 和 setter 方法省略
}
导出 Excel
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.WriteSheet;

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

public class ExcelExportUtil {

    public static void exportPersonList(HttpServletResponse response, List<PersonVO> personList) {
        String fileName = "人员信息表.xlsx";
        String sheetName = "人员信息表";

        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            OutputStream outputStream = response.getOutputStream();
            // 写入 Excel 文件
            EasyExcel.write(outputStream, PersonVO.class)
                    .sheet(sheetName)
                    .doWrite(personList);

            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
导入 Excel
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class ExcelImportUtil {

    public static List<PersonVO> importPersonList(MultipartFile file) {
        List<PersonVO> personList = new ArrayList<>();

        try {
            EasyExcel.read(file.getInputStream(), PersonVO.class, new ReadListener<PersonVO>() {
                @Override
                public void invoke(PersonVO data, AnalysisContext analysisContext) {
                    personList.add(data);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                }
            }).sheet().doRead();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return personList;
    }
}

以上是使用 Apache POI 和 EasyExcel 实现 Excel 表格导入导出功能的具体代码示例。你可以根据实际需求选择合适的方法进行开发。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2343953.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Websocket自动发送消息客户端工具

点击下载《Websocket自动发送消息客户端工具》 1. 前言 在现代网络应用中&#xff0c;实时通信和即时数据传输变得越来越重要。WebSocket作为一种全双工通信协议&#xff0c;因其高效、实时的特点&#xff0c;被广泛应用于聊天应用、实时数据监控、在线游戏等领域。然而&…

STM32的开发环境介绍

目录 STM32软件环境 Keil软件在线安装 其他软件环境安装 STM32开发的几种方式 STM32寄存器版本和库函数版本 标准外设库的作用&#xff1a; STM32软件环境 STM32 的集成开发环境&#xff08;IDE&#xff09;&#xff1a;编辑编译软件 常见的环境&#xff1a; (1)KEIL&a…

数据库系统概论(四)关系操作,关系完整性与关系代数

数据库系统概论&#xff08;四&#xff09;详细讲解关系操作&#xff0c;关系完整性与关系代数 前言一、什么是关系操作1.1 基本的关系操作1.2 关系数据语言的分类有哪些 二、关系的完整性2.1 实体完整性2.2 参照完整性2.3 用户的定义完整性 三、关系代数是什么3.1 传统的集合运…

基于 IPMI + Kickstart + Jenkins 的 OS 自动化安装

Author&#xff1a;Arsen Date&#xff1a;2025/04/26 目录 环境要求实现步骤自定义 ISO安装 ipmitool安装 NFS定义 ks.cfg安装 HTTP编写 Pipeline 功能验证 环境要求 目标服务器支持 IPMI / Redfish 远程管理&#xff08;如 DELL iDRAC、HPE iLO、华为 iBMC&#xff09;&…

使用 Node、Express 和 MongoDB 构建一个项目工程

本文将详细介绍如何使用 Node.js Express MongoDB 构建一个完整的 RESTful API 后端项目&#xff0c;涵盖&#xff1a; 项目初始化 Express 服务器搭建 MongoDB 数据库连接 REST API 设计&#xff08;CRUD 操作&#xff09; 错误处理与中间件 源码结构与完整代码 部署建…

【C++11】右值引用和移动语义:万字总结

&#x1f4dd;前言&#xff1a; 这篇文章我们来讲讲右值引用和移动语义 &#x1f3ac;个人简介&#xff1a;努力学习ing &#x1f4cb;个人专栏&#xff1a;C学习笔记 &#x1f380;CSDN主页 愚润求学 &#x1f304;其他专栏&#xff1a;C语言入门基础&#xff0c;python入门基…

Python基于Django的全国二手房可视化分析系统【附源码】

博主介绍&#xff1a;✌Java老徐、7年大厂程序员经历。全网粉丝12w、csdn博客专家、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精彩专栏推荐订阅&#x1f447;&…

VulnHub-DC-2靶机渗透教程

VulnHub-DC-2靶机渗透教程 1.靶机部署 [Onepanda] Mik1ysomething 靶机下载&#xff1a;https://download.vulnhub.com/dc/DC-2.zip 直接使用VMware导入打开就行 2.信息收集 2.1 获取靶机ip(arp-scan/nmap) arp-scan -l ​ nmap 192.168.135.0/24 2.2 详细信息扫描(nmap)…

n8n 中文系列教程_10. 解析n8n中的AI节点:从基础使用到高级Agent开发

在自动化工作流中集成AI能力已成为提升效率的关键。n8n通过内置的LangChain节点&#xff0c;让开发者无需复杂代码即可快速接入GPT-4、Claude等大模型&#xff0c;实现文本处理、智能决策等高级功能。本文将深入解析n8n的AI节点体系&#xff0c;从基础的Basic LLM Chain到强大的…

计算机网络 | 应用层(1)--应用层协议原理

&#x1f493;个人主页&#xff1a;mooridy &#x1f493;专栏地址&#xff1a;《计算机网络&#xff1a;自定向下方法》 大纲式阅读笔记 关注我&#x1f339;&#xff0c;和我一起学习更多计算机的知识 &#x1f51d;&#x1f51d;&#x1f51d; 目录 1. 应用层协议原理 1.1 …

MuJoCo 关节角速度记录与可视化,监控机械臂运动状态

视频讲解&#xff1a; MuJoCo 关节角速度记录与可视化&#xff0c;监控机械臂运动状态 代码仓库&#xff1a;GitHub - LitchiCheng/mujoco-learning 关节空间的轨迹优化&#xff0c;实际上是对于角速度起到加减速规划的控制&#xff0c;故一般来说具有该效果的速度变化会显得丝…

LVGL模拟器:NXP GUIDER+VSCODE

1. 下载安装包 NXP GUIDER&#xff1a;GUI Guider | NXP 半导体 CMAKE&#xff1a;Download CMake MINGW&#xff1a;https://github.com/niXman/mingw-builds-binaries/releases SDL2&#xff1a;https://github.com/libsdl-org/SDL/releases/tag/release-2.30.8 VSCODE&…

《USB技术应用与开发》第四讲:实现USB鼠标

一、标准鼠标分析 1.1简介 1.2页面显示 其中页面显示的“”不用管它&#xff0c;因为鼠标作为物理抓包&#xff0c;里面有时候会抓到一些错误&#xff0c;不一定是真正的通讯错误&#xff0c;很可能是本身线路接触质量不好等原因才打印出来的“”。 1.3按下鼠标左键 &#x…

一、鸿蒙编译篇

一、下载源码和编译 https://blog.csdn.net/xusiwei1236/article/details/142675221 https://blog.csdn.net/xiaolizibie/article/details/146375750 https://forums.openharmony.cn/forum.php?modviewthread&tid897 repo init -u https://gitee.com/openharmony/mani…

得物业务参数配置中心架构综述

一、背景 现状与痛点 在目前互联网飞速发展的今天&#xff0c;企业对用人的要求越来越高&#xff0c;尤其是后端的开发同学大部分精力都要投入在对复杂需求的处理&#xff0c;以及代码架构&#xff0c;稳定性的工作中&#xff0c;在对比下&#xff0c;简单且重复的CRUD就显得…

【算法】单词搜索、最短距离

单词搜索 这道题主要考察了深度优先遍历(DFS)算法。 我们通过几个简单例子来分析一些细节问题&#xff1a; 1. 要搜索的单词串&#xff1a;abc 搜索的过程中必须按照字母顺序&#xff0c;首先从矩阵中的第一个元素开始搜索&#xff0c;遇到字母a则开始深度优先遍历&#xff0…

Python函数基础:简介,函数的定义,函数的调用和传入参数,函数的返回值

目录 函数简介 函数定义&#xff0c;调用&#xff0c;传入参数&#xff0c;返回值 函数的定义 函数的调用和传入参数 函数的返回值 函数简介 函数简介&#xff1a;函数是组织好&#xff0c;可重复使用&#xff0c;用来实现特定功能&#xff08;特定需求&#xff09;的代码…

基于FFmpeg命令行的实时图像处理与RTSP推流解决方案

前言 在一些项目开发过程中需要将实时处理的图像再实时的将结果展示出来&#xff0c;此时如果再使用一张一张图片显示的方式展示给开发者&#xff0c;那么图像窗口的反复开关将会出现窗口闪烁的问题&#xff0c;实际上无法体现出动态画面的效果。因此&#xff0c;需要使用码流…

【随笔】地理探测器原理与运用

文章目录 一、作者与下载1.1 软件作者1.2 软件下载 二、原理简述2.1 空间分异性与地理探测器的提出2.2 地理探测器的数学模型2.21 分异及因子探测2.22 交互作用探测2.23 风险区与生态探测 三、使用&#xff1a;excel 一、作者与下载 1.1 软件作者 作者&#xff1a; DOI: 10.…

从零开始使用SSH链接目标主机(包括Github添加SSH验证,主机连接远程机SSH验证)

添加ssh密钥(当前机生成和远程机承认) 以下是从头开始生成自定义名称的SSH密钥的完整步骤&#xff08;以GitHub为例&#xff0c;适用于任何SSH服务&#xff09;&#xff1a; 1. 生成自定义名称的SSH密钥对 # 生成密钥对&#xff08;-t 指定算法&#xff0c;-f 指定路径和名称…