java入门019~springboot批量导入excel数据到mysql

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: java入门019~springboot批量导入excel数据到mysql

我们在前面的章节已经讲了如何用jpa或者mybatis来操作mysql数据库。这一节我们就来结合具体案例,来讲解下excel表格的上传,与excel表里数据的识别。并把识别后的数据批量导入到mysql数据库


所用知识点


  • springboot 2.1.9
  • excel文件上传
  • excel数据批量识别
  • excel数据上传到mysql数据库
  • jpa的使用

jpa的使用我们在上一节已经给大家讲过了,不知道如何创建的亲,记得去翻看上一节的文章:《java入门018~springboot2使用JPA操作mysql数据库》


一,创建一个springboot项目


1,使用idea创建springboot项目



点击finish即可


二,引入识别excel的poi 和poi-ooxml类库



完整的pom.xml贴出来给大家


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--  操作excel      -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

记得重新Reimport



三,创建一个controller用于接收上传的excel文件



完整代码如下


package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;
/**
 * 2019-10-07 18:35
 * author: 编程小石头
 * wechat:2501902696
 * desc: 把excel里的数据保存到mysql数据库里
 */
@Controller
public class ExcelController {
    @GetMapping("/index")
    public String index() {
        return "index";
    }
    @RequestMapping("/uploadExcel")
    @ResponseBody
    public String uploadExcel(@RequestParam("file") MultipartFile file,
                              Map<String, Object> map) {
        String name = file.getOriginalFilename();
        if (name.length() < 6 || !name.substring(name.length() - 5).equals(".xlsx")) {
            return "文件格式错误";
        }
        List<ExcelBean> list = null;
        try {
            list = ExcelUtils.excelToShopIdList(file.getInputStream());
            if (list == null || list.size() <= 0) {
                return "导入的数据为空";
            }
            //excel的数据保存到数据库
            try {
                for (ExcelBean excel : list) {
                    System.out.println(excel.toString());
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
                return e.getMessage();
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
        return "保存成功";
    }
}

简单讲解下上面代码的步骤

  • 1,获取用户上传的excel文件
  • 2,获取file流
  • 3,把excel文件流传入ExcelUtils.excelToShopIdList来识别excel里的数据
  • ExcelUtils很重要,是我们识别excel的重要步骤


四,ExcelUtils类如下


package com.example.demo;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/*
 * 操作excel
 * */
public class ExcelUtils {
    public static List<ExcelBean> excelToShopIdList(InputStream inputStream) {
        List<ExcelBean> list = new ArrayList<>();
        Workbook workbook = null;
        try {
            workbook = WorkbookFactory.create(inputStream);
            inputStream.close();
            //工作表对象
            Sheet sheet = workbook.getSheetAt(0);
            //总行数
            int rowLength = sheet.getLastRowNum();
            //            System.out.println("总行数有多少行" + rowLength);
            //工作表的列
            Row row = sheet.getRow(0);
            //总列数
            int colLength = row.getLastCellNum();
            //            System.out.println("总列数有多少列" + colLength);
            //得到指定的单元格
            Cell cell = row.getCell(0);
            for (int i = 1; i <= rowLength; i++) {
                ExcelBean jiFenExcel = new ExcelBean();
                row = sheet.getRow(i);
                for (int j = 0; j < colLength; j++) {
                    //列: 0姓名    1人员编号   2餐补 3部门
                    cell = row.getCell(j);
                    //                    System.out.print(cell + ",");
                    if (cell != null) {
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String data = cell.getStringCellValue();
                        data = data.trim();
                        //                        System.out.print(data);
                        //                        if (StringUtils.isNumeric(data)) {
                        if (j == 0) {
                            jiFenExcel.setName(data);
                        } else if (j == 1) {
                            jiFenExcel.setJobNum(data);
                        } else if (j == 2) {
                            jiFenExcel.setCanBu(Integer.parseInt(data));
                        } else if (j == 3) {
                            jiFenExcel.setBumen(data);
                        }
                        //                        }
                    }
                }
                list.add(jiFenExcel);
                //                System.out.println("====");
            }
        } catch (Exception e) {
        }
        return list;
    }
}


五,定义一个用于上传excel文件的html静态网页


我们的index.html位于resources下的static里



代码如下


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传excel</title>
</head>
<body>
<h1>上传excel文件并存入到mysql数据库</h1>
<form action="/uploadExcel" method="post" enctype="multipart/form-data">
    <p>文件上传</p>
    <input type="file" name="file">
    <p><input type="submit" value="提交"></p>
</form>
</body>
</html>


六,编写配置文件



这一步是让springboot可以直接访问我们上面第五步定义的静态html网页。


七,运行项目



运行起来后,我们通过index.html网页,来上传我们桌面的excel文件。



八,识别excel表格内容。


我们excel表格内容如下



我们通过上面第七步,上传excel到服务器后,识别出来的数据如下



通过上图可以看出,我们成功的识别出了excel里的数据。


既然数据已经识别出来了,接下来就是通过一个for循环,把我们识别出来的5行数据,批量的存到数据里就可以了。

今天就先到这里,下一节来讲如何把这些数据存到mysql数据库里。

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
23天前
|
存储 监控 关系型数据库
轻松入门Mysql:MySQL性能优化与监控,解锁进销存系统的潜力(23)
轻松入门Mysql:MySQL性能优化与监控,解锁进销存系统的潜力(23)
|
23天前
|
SQL 数据可视化 关系型数据库
轻松入门MySQL:深入探究MySQL的ER模型,数据库设计的利器与挑战(22)
轻松入门MySQL:深入探究MySQL的ER模型,数据库设计的利器与挑战(22)
105 0
|
23天前
|
存储 关系型数据库 MySQL
轻松入门MySQL:数据库设计之范式规范,优化企业管理系统效率(21)
轻松入门MySQL:数据库设计之范式规范,优化企业管理系统效率(21)
|
19天前
|
存储 关系型数据库 MySQL
MySQL基础入门:数据库操作全攻略
MySQL基础入门:数据库操作全攻略
48 0
|
2天前
|
Java 开发工具 Windows
Java入门及环境变量
Java入门及环境变量
|
2天前
|
Java API 调度
[AIGC] 深入理解Java并发编程:从入门到进阶
[AIGC] 深入理解Java并发编程:从入门到进阶
|
2天前
|
Java Nacos 开发者
Java从入门到精通:4.2.1学习新技术与框架——以Spring Boot和Spring Cloud Alibaba为例
Java从入门到精通:4.2.1学习新技术与框架——以Spring Boot和Spring Cloud Alibaba为例
|
2天前
|
前端开发 Java 测试技术
Java从入门到精通:4.1.1参与实际项目,锻炼编程与问题解决能力
Java从入门到精通:4.1.1参与实际项目,锻炼编程与问题解决能力
|
2天前
|
Java 程序员 数据库连接
Java从入门到精通:3.3.2性能优化与调优——内存管理篇
Java从入门到精通:3.3.2性能优化与调优——内存管理篇
Java从入门到精通:3.3.2性能优化与调优——内存管理篇
|
2天前
|
Dubbo Java 应用服务中间件
Java从入门到精通:3.2.2分布式与并发编程——了解分布式系统的基本概念,学习使用Dubbo、Spring Cloud等分布式框架
Java从入门到精通:3.2.2分布式与并发编程——了解分布式系统的基本概念,学习使用Dubbo、Spring Cloud等分布式框架