SpringBoot使用EasyPoi将Mysql数据库中的数据导出到Excel文件中并把Excel文件中的数据导入到Mysql数据库中

项目的文件结构:

SpringBoot使用EasyPoi将Mysql数据库中的数据导出到Excel文件中并把Excel文件中的数据导入到Mysql数据库中_第1张图片

导入jar包:pom.xml

<dependencies>
        <!--数据库连接相关的依赖以及一些其它必要的依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--使用easypoi需要的三个依赖-->
        <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>
        <!--lombok的依赖,用于简化实体类  @Data 相当于实体类中的 get set 和String-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!-- 文件上传组件 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!--阿里巴巴 fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.30</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-annotation</artifactId>
            <version>3.0.6</version>
        </dependency>
        <!--引入mybatis 这是mybatis官方提出适配springboot的 而不是 springboot自己的-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <!--使用thymeleaf 模板需要的依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>

sql数据库文件

点击下载:sql数据库文件
SpringBoot使用EasyPoi将Mysql数据库中的数据导出到Excel文件中并把Excel文件中的数据导入到Mysql数据库中_第2张图片

工具类:ExtUtils.java

package com.yrj.utils;

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.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

/**
 * @author yirj
 * @date 2020/4/16 11:08
 */
public class ExtUtils {
    private static final java.net.URLEncoder URLEncoder = null;

    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 NormalException(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 NormalException("模板不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            // throw new NormalException(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 NormalException("excel文件不能为空");
        } catch (Exception e) {
            // throw new NormalException(e.getMessage());
            System.out.println(e.getMessage());
        }
        return list;
    }
}

配置:application.yml

server:
  port: 8082
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/testuser?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=UTC
    username: root
    password: root
mybatis:
  mapper-locations: classpath:/mapper/UserMapper.xml
  type-aliases-package: com.yrj.entity
thymeleaf:
  prefix: classpath:/templates
  check-template-location: true
  cache: false
  suffix:  .html
  mode: HTML5

实体类:User.java

package com.yrj.entity;

import cn.afterturn.easypoi.excel.annotation.Excel;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.io.Serializable;
import java.util.Date;

/**
 * @author yirj
 * @date 2020/4/16 11:14
 */
@Data
@TableName("user")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    @Excel(name = "id", width = 15)
    @TableId("id")
    private int id;

    @Excel(name = "姓名", width = 15)
    @TableField("name")
    private String name;

    @Excel(name = "年龄", width = 15)
    @TableField("age")
    private int age;

    @Excel(name = "出生日期" ,width = 30,format = "yyyy-MM-dd HH:mm:ss")
    @TableField("start_time")
    private Date startTime;

    @Excel(name = "死亡日期" ,width = 30,format = "yyyy-MM-dd HH:mm:ss")
    @TableField("end_time")
    private Date endTime;
}

接口类:UserMapper.interface

package com.yrj.mapper;

import com.yrj.entity.User;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.Mapping;

import java.util.List;

/**
 * @author yirj
 * @date 2020/4/16 11:52
 */
@Repository
public interface UserMapper {
    //查询数据库中所有的用户数据
    List<User> selectAllUser();
    //将excel中的数据导入到数据库中
    void addAllUser(User user);
}

mapper文件: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.yrj.mapper.UserMapper">
    <select id="selectAllUser" resultType="User">
        select * from testuser
    </select>
    <insert id="addAllUser" parameterType="User">
        insert into testuser (name, age,startTime,endTime) values (#{name},#{age},#{startTime},#{endTime})
    </insert>
</mapper>

Service层:UserService.interface

package com.yrj.service;

import com.yrj.entity.User;

import java.util.List;

/**
 * @author yirj
 * @date 2020/4/16 13:41
 */
public interface UserService {
    List<User> selectAllUser();
    void addAllUser(User user);
}

Service实现层:UserServiceImpl.java

package com.yrj.service;

import com.yrj.entity.User;
import com.yrj.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.beans.IntrospectionException;
import java.util.List;

/**
 * @author yirj
 * @date 2020/4/16 13:43
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> selectAllUser() {
        return userMapper.selectAllUser();
    }

    @Override
    public void addAllUser(User user) {
        userMapper.addAllUser(user);
    }
}

控制层:ExcelController.java

package com.yrj.controller;

import com.yrj.entity.User;
import com.yrj.service.UserServiceImpl;
import com.yrj.utils.ExtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @author yirj
 * @date 2020/4/16 11:19
 */
@Controller
public class ExcelController {
    @Autowired
    private UserServiceImpl userService;

    //跳转到用户下载数据库生成的excel文件的页面   http://localhost:8082/toExport
    @RequestMapping("/toExport")
    public String toExport(){
        return "export";
    }

    //将数据库中的所有的数据导入到excel表中,生成excel文件。
    @RequestMapping("/export1")
    public void export(HttpServletResponse response) {
        List<User> user = userService.selectAllUser();
        ExtUtils.exportExcel(user, "easypoi导出数据库中的数据", "sheet名字", User.class, "文件名称.xls", response);
    }

    //跳转到用户上传excel中的数据到数据库的页面   http://localhost:8082/toImport
    @RequestMapping("/toImport")
    public String toImport(){
        return "import";
    }

    //将excel表中的所有的数据导入到数据库中,数据库中的id是自动递增的
    @PostMapping("/import1")
    @ResponseBody
    public String import1(@RequestParam("file") MultipartFile file){
        //解析excel,获取excel中的数据 并逐条导入到数据库中
        List<User> userList = ExtUtils.importExcel(file, 1, 1, User.class);
        for (User user : userList) {
            userService.addAllUser(user);
        }
        return "数据导入成功--->本次共导入【"+userList.size()+"】行数据";
    }
}

启动类:SpringbootEasypoiDataApplication.java

package com.yrj;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(value = "com.yrj.mapper")
public class SpringbootEasypoiDataApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootEasypoiDataApplication.class, args);
    }
}

前端导入页面:import.html
访问地址:http://localhost:8082/toImport

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>文件导入上传</title>
</head>
<body align="center">
<h2>上传导入excel文件中的数据到数据库中</h2>
<form method="post" enctype="multipart/form-data" id="form" th:action="@{/import1}">
    <input type="file" name="file"/>
    <input type="submit" value="上传文件"/>
</form>
<hr>
</body>
</html>

SpringBoot使用EasyPoi将Mysql数据库中的数据导出到Excel文件中并把Excel文件中的数据导入到Mysql数据库中_第3张图片

前端导出页面:export.html
访问地址:http://localhost:8082/toExport

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>文件导出下载</title>
</head>
<body align="center">
<h2>下载导出数据库中的数据到excel文件中</h2>
<form method="get" enctype="multipart/form-data" id="form" th:action="@{/export1}">
    <input type="submit" value="下载文件"/>
</form>
<hr>
</body>
</html>

SpringBoot使用EasyPoi将Mysql数据库中的数据导出到Excel文件中并把Excel文件中的数据导入到Mysql数据库中_第4张图片
我小白一枚,写这个东东也踩了很多坑,在网上也看了很多文章,也记不得看了那些了,这些文章通过自己的整理也慢慢的整理出了这么一个,也实现了相关的功能!
文章难免有不足之处,请大佬勿喷。用心讨论,共同提升!
源码在这里就不放了,上面贴的代码已经很详细了!

你可能感兴趣的:(SpringBoot,EasyPoi,thymeleaf)