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


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

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
5月前
|
Python
如何根据Excel某列数据为依据分成一个新的工作表
在处理Excel数据时,我们常需要根据列值将数据分到不同的工作表或文件中。本文通过Python和VBA两种方法实现该操作:使用Python的`pandas`库按年级拆分为多个文件,再通过VBA宏按班级生成新的工作表,帮助高效整理复杂数据。
|
5月前
|
数据采集 数据可视化 数据挖掘
用 Excel+Power Query 做电商数据分析:从 “每天加班整理数据” 到 “一键生成报表” 的配置教程
在电商运营中,数据是增长的关键驱动力。然而,传统的手工数据处理方式效率低下,耗费大量时间且易出错。本文介绍如何利用 Excel 中的 Power Query 工具,自动化完成电商数据的采集、清洗与分析,大幅提升数据处理效率。通过某美妆电商的实战案例,详细拆解从多平台数据整合到可视化报表生成的全流程,帮助电商从业者摆脱繁琐操作,聚焦业务增长,实现数据驱动的高效运营。
|
3月前
|
SQL 关系型数据库 MySQL
如何将Excel表的数据导入RDS MySQL数据库?
本文介绍如何通过数据管理服务DMS将Excel文件(转为CSV格式)导入RDS MySQL数据库,涵盖建表、编码设置、导入模式选择及审批执行流程,并提供操作示例与注意事项。
|
7月前
|
存储 安全 大数据
网安工程师必看!AiPy解决fscan扫描数据整理难题—多种信息快速分拣+Excel结构化存储方案
作为一名安全测试工程师,分析fscan扫描结果曾是繁琐的手动活:从海量日志中提取开放端口、漏洞信息和主机数据,耗时又易错。但现在,借助AiPy开发的GUI解析工具,只需喝杯奶茶的时间,即可将[PORT]、[SERVICE]、[VULN]、[HOST]等关键信息智能分类,并生成三份清晰的Excel报表。告别手动整理,大幅提升效率!在安全行业,工具党正碾压手动党。掌握AiPy,把时间留给真正的攻防实战!官网链接:https://www.aipyaipy.com,解锁更多用法!
|
5月前
|
Python
将Excel特定某列数据删除
将Excel特定某列数据删除
|
3月前
|
缓存 关系型数据库 BI
使用MYSQL Report分析数据库性能(下)
使用MYSQL Report分析数据库性能
135 3
|
3月前
|
关系型数据库 MySQL 数据库
自建数据库如何迁移至RDS MySQL实例
数据库迁移是一项复杂且耗时的工程,需考虑数据安全、完整性及业务中断影响。使用阿里云数据传输服务DTS,可快速、平滑完成迁移任务,将应用停机时间降至分钟级。您还可通过全量备份自建数据库并恢复至RDS MySQL实例,实现间接迁移上云。
|
4月前
|
存储 运维 关系型数据库
从MySQL到云数据库,数据库迁移真的有必要吗?
本文探讨了企业在业务增长背景下,是否应从 MySQL 迁移至云数据库的决策问题。分析了 MySQL 的优势与瓶颈,对比了云数据库在存储计算分离、自动化运维、多负载支持等方面的优势,并提出判断迁移必要性的五个关键问题及实施路径,帮助企业理性决策并落地迁移方案。
|
3月前
|
关系型数据库 MySQL 分布式数据库
阿里云PolarDB云原生数据库收费价格:MySQL和PostgreSQL详细介绍
阿里云PolarDB兼容MySQL、PostgreSQL及Oracle语法,支持集中式与分布式架构。标准版2核4G年费1116元起,企业版最高性能达4核16G,支持HTAP与多级高可用,广泛应用于金融、政务、互联网等领域,TCO成本降低50%。
|
3月前
|
关系型数据库 MySQL 数据库
阿里云数据库RDS费用价格:MySQL、SQL Server、PostgreSQL和MariaDB引擎收费标准
阿里云RDS数据库支持MySQL、SQL Server、PostgreSQL、MariaDB,多种引擎优惠上线!MySQL倚天版88元/年,SQL Server 2核4G仅299元/年,PostgreSQL 227元/年起。高可用、可弹性伸缩,安全稳定。详情见官网活动页。

推荐镜像

更多