Springboot 最简单的结合MYSQL数据实现EXCEL表格导出及数据导入

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介: Springboot 最简单的结合MYSQL数据实现EXCEL表格导出及数据导入

嗯,今天如题,给大家介绍下最最最简单的实现excel导入导出的功能,功能简单叙述:


导入:读取本地的excel表格,将里面的内容都插入对应的数据库表(批量插入)


导出:读取数据库表内容,将其导出到excel文件


进入正题前,还是啰嗦一下,为啥要做一个这样的简单实战介绍呢,因为现在网上很多结合poi实现excel导入导出的教程不是太花了,就是各种版本老旧,所以在此,我也是等于提炼一下可用的,等于结合实战给大家一个最新的,最简单的教程例子。


OK,开始贴码实战(至于连接mybatis的整合以及查询MYSQL这些就不做介绍了,这是前提,我们不用模拟数据,当然你可以用也就是模拟个List而已嘛):


<!-- 导入和导出-->
<dependency>
   <groupId>cn.afterturn</groupId>
   <artifactId>easypoi-base</artifactId>
   <version>3.0.3</version>
</dependency>
<dependency>
   <groupId>cn.afterturn</groupId>
   <artifactId>easypoi-web</artifactId>
   <version>3.0.3</version>
</dependency>
<dependency>
   <groupId>cn.afterturn</groupId>
   <artifactId>easypoi-annotation</artifactId>
   <version>3.0.3</version>
</dependency>


OK,创建个实体类,User.java:


package com.example.tdemo.pojo;
import cn.afterturn.easypoi.excel.annotation.Excel;
public class User {
    @Excel(name = "学号", orderNum = "0")
    private Integer id;
    @Excel(name = "姓名", orderNum = "1")
    private String  userName;
    @Excel(name = "年龄", orderNum = "2")
    private String  userAge;
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", userAge='" + userAge + '\'' +
                '}';
    }
    public User() {
    }
    public User(Integer id, String userName, String userAge) {
        this.id = id;
        this.userName = userName;
        this.userAge = userAge;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserAge() {
        return userAge;
    }
    public void setUserAge(String userAge) {
        this.userAge = userAge;
    }
}


然后是 excel导入导出的工具类,ExcelUtil:


package com.example.tdemo.util;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
public class ExcelUtil {
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName,boolean isCreateHeader, HttpServletResponse response){
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }
    //导出
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response){
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
        defaultExport(list, fileName, response);
    }
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }
    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }
    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }
    //导入
    public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){
        if (StringUtils.isBlank(filePath)){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        }catch (NoSuchElementException e){
            throw new RuntimeException("模板不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        return list;
    }
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
        if (file == null){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        }catch (NoSuchElementException e){
            throw new RuntimeException("excel文件不能为空");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return list;
    }
}


接下来玩导出导入,


既然是结和MYSQL数据库,那么我们简单看看,表,毕竟刚刚也创建了实体类:


image.png


好了,然后UserMapper简单贴一下:


@Mapper
public interface UserMapper {
    //查询所有
    List<User> queryUserInfo();
    //插入所有
    void addUserInfo(List<User> list);
}


相关的 userMapper.xml:


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.tdemo.mapper.UserMapper">
    <!--查询所有用户信息-->
    <select id="queryUserInfo" resultType="com.example.tdemo.pojo.User">
        select *
        from user
    </select>
    <!--批量插入信息-->
    <insert id="addUserInfo" parameterType="java.util.List">
        insert into user(
        user_name,
        user_age
        )
        values
        <foreach collection="list" item="item" index= "index" separator =",">
            (
            #{item.userName},
            #{item.userAge}
            )
        </foreach>
    </insert>
</mapper>


然后是UserService:


public interface UserService {
    //查询所有
    List<User> queryUserInfo();
    //插入所有
    void addUserInfo(List<User> list);
}


对应的实现类:


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public List<User> queryUserInfo() {
        return userMapper.queryUserInfo();
    }
    @Override
    public void addUserInfo(List<User> list) {
       userMapper.addUserInfo(list);
    }
}


好了,开始导出导入了!


我们直接看代码,创建一个TestController,


package com.example.tdemo.controller;
import com.example.tdemo.pojo.User;
import com.example.tdemo.service.impl.UserServiceImpl;
import com.example.tdemo.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@RestController
public class TestController {
    @Autowired
    UserServiceImpl userService;
    @RequestMapping("exportExcel")
    public void export(HttpServletResponse response){
        List<User> userList = userService.queryUserInfo();
        //导出操作
        ExcelUtil.exportExcel(userList,"用户信息","sheet1",User.class,"testDATA.xls",response);
    }
    @RequestMapping("importExcel")
    public String importExcel(){
        String filePath = "C:\\testInfo.xls";
        //解析excel,
        List<User> userList = ExcelUtil.importExcel(filePath,1,1,User.class);
        //也可以使用MultipartFile,使用 FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)导入
        System.out.println("导入数据一共【"+userList.size()+"】行");
        userService.addUserInfo(userList);
        List<User> userList2 = userService.queryUserInfo();
        return userList2.toString();
    }
}


好像结束了,我们来简单调下接口,验证下吧:


导出前数据表数据是这样的:


image.png


调用导出接口(谷歌浏览器默认下载到对应路径,IE\360等浏览器可以选择导出下载地址):


image.png


OK,EXCEL表格已经导出,我们看看打开看看:


image.png那我们继续调下导入吧(记得看下对应的接口,导入选择的路径我们是写死的,文件名也是,后期结合前端交互可以改为路径选择传入),


先看看需要导入数据的EXCEL表格内容,


image.png好,开始调用导入接口(将EXCEL表格内容转化为List,再将List数据批量插入数据库):

image.png


OK,我们导入数据,插入数据库后打印出来当前表信息,其实已经可以确定,肯定是无误了,最后看看数据库:


image.png


好了,就到此结束吧,是不是很简单?

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
12天前
|
数据采集 存储 JavaScript
自动化数据处理:使用Selenium与Excel打造的数据爬取管道
本文介绍了一种使用Selenium和Excel结合代理IP技术从WIPO品牌数据库(branddb.wipo.int)自动化爬取专利信息的方法。通过Selenium模拟用户操作,处理JavaScript动态加载页面,利用代理IP避免IP封禁,确保数据爬取稳定性和隐私性。爬取的数据将存储在Excel中,便于后续分析。此外,文章还详细介绍了Selenium的基本设置、代理IP配置及使用技巧,并探讨了未来可能采用的更多防反爬策略,以提升爬虫效率和稳定性。
|
9天前
|
数据处理 Python
Python实用记录(十):获取excel数据并通过列表的形式保存为txt文档、xlsx文档、csv文档
这篇文章介绍了如何使用Python读取Excel文件中的数据,处理后将其保存为txt、xlsx和csv格式的文件。
27 3
Python实用记录(十):获取excel数据并通过列表的形式保存为txt文档、xlsx文档、csv文档
|
12天前
|
easyexcel Java UED
SpringBoot中大量数据导出方案:使用EasyExcel并行导出多个excel文件并压缩zip后下载
在SpringBoot环境中,为了优化大量数据的Excel导出体验,可采用异步方式处理。具体做法是将数据拆分后利用`CompletableFuture`与`ThreadPoolTaskExecutor`并行导出,并使用EasyExcel生成多个Excel文件,最终将其压缩成ZIP文件供下载。此方案提升了导出效率,改善了用户体验。代码示例展示了如何实现这一过程,包括多线程处理、模板导出及资源清理等关键步骤。
|
9天前
|
Java 关系型数据库 MySQL
springboot学习五:springboot整合Mybatis 连接 mysql数据库
这篇文章是关于如何使用Spring Boot整合MyBatis来连接MySQL数据库,并进行基本的增删改查操作的教程。
14 0
springboot学习五:springboot整合Mybatis 连接 mysql数据库
|
9天前
|
Java 关系型数据库 MySQL
springboot学习四:springboot链接mysql数据库,使用JdbcTemplate 操作mysql
这篇文章是关于如何使用Spring Boot框架通过JdbcTemplate操作MySQL数据库的教程。
11 0
springboot学习四:springboot链接mysql数据库,使用JdbcTemplate 操作mysql
|
16天前
|
XML 关系型数据库 MySQL
MySQL 导出某些数据的技术详解
MySQL 导出某些数据的技术详解
68 2
|
18天前
|
前端开发 Java 数据库连接
表白墙/留言墙 —— 中级SpringBoot项目,MyBatis技术栈MySQL数据库开发,练手项目前后端开发(带完整源码) 全方位全步骤手把手教学
本文是一份全面的表白墙/留言墙项目教程,使用SpringBoot + MyBatis技术栈和MySQL数据库开发,涵盖了项目前后端开发、数据库配置、代码实现和运行的详细步骤。
24 0
表白墙/留言墙 —— 中级SpringBoot项目,MyBatis技术栈MySQL数据库开发,练手项目前后端开发(带完整源码) 全方位全步骤手把手教学
|
29天前
|
SQL 关系型数据库 MySQL
springboot项目操作mysql出现锁表问题情况
springboot项目操作mysql出现锁表问题情况
29 2
|
9天前
|
存储 SQL 关系型数据库
Mysql学习笔记(二):数据库命令行代码总结
这篇文章是关于MySQL数据库命令行操作的总结,包括登录、退出、查看时间与版本、数据库和数据表的基本操作(如创建、删除、查看)、数据的增删改查等。它还涉及了如何通过SQL语句进行条件查询、模糊查询、范围查询和限制查询,以及如何进行表结构的修改。这些内容对于初学者来说非常实用,是学习MySQL数据库管理的基础。
43 6
|
7天前
|
存储 关系型数据库 MySQL
Mysql(4)—数据库索引
数据库索引是用于提高数据检索效率的数据结构,类似于书籍中的索引。它允许用户快速找到数据,而无需扫描整个表。MySQL中的索引可以显著提升查询速度,使数据库操作更加高效。索引的发展经历了从无索引、简单索引到B-树、哈希索引、位图索引、全文索引等多个阶段。
39 3
Mysql(4)—数据库索引