• 【项目实操】本地excel文档内容传到数据库中


    一、创建数据库

    CREATE TABLE `edu_subject` (
      `id` char(19) DEFAULT NULL COMMENT '课程类别ID',
      `title` varchar(10) NOT NULL COMMENT '类别名称',
      `parent_id` char(19) NOT NULL DEFAULT '0' COMMENT '父ID',
      `sort` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '排序字段',
      `gmt_create` datetime NOT NULL COMMENT '创建时间',
      `gmt_modified` datetime NOT NULL COMMENT '更新时间',
      KEY `idx_parent_id` (`parent_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT COMMENT='课程科目'
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在这里插入图片描述

    二、导入相应依赖

    <dependency>
    	 <groupId>com.alibabagroupId>
         <artifactId>easyexcelartifactId>
         <version>2.1.1version>
    dependency>
    <dependency>
         <groupId>org.apache.poigroupId>
         <artifactId>poiartifactId>
         <version>3.17version>
    dependency>
    <dependency>
        <groupId>org.apache.poigroupId>
        <artifactId>poi-ooxmlartifactId>
        <version>3.17version>
    dependency>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    项目架构
    在这里插入图片描述

    三、使用MP代码生成器

    导入依赖:

     
            <dependency>
                <groupId>com.baomidougroupId>
                <artifactId>mybatis-plus-generatorartifactId>
                <version>3.0.5version>
            dependency>
            <dependency>
                <groupId>org.apache.velocitygroupId>
                <artifactId>velocity-engine-coreartifactId>
                <version>2.0version>
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    package com.jin;
    
    import com.baomidou.mybatisplus.annotation.DbType;
    import com.baomidou.mybatisplus.annotation.IdType;
    import com.baomidou.mybatisplus.generator.AutoGenerator;
    import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
    import com.baomidou.mybatisplus.generator.config.GlobalConfig;
    import com.baomidou.mybatisplus.generator.config.PackageConfig;
    import com.baomidou.mybatisplus.generator.config.StrategyConfig;
    import com.baomidou.mybatisplus.generator.config.rules.DateType;
    import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
    import org.junit.Test;
    
    public class CodeGenerator {
    
        @Test
        public void getCode() {
    // 1、创建代码生成器
            AutoGenerator mpg = new AutoGenerator();
    // 2、全局配置
            GlobalConfig gc = new GlobalConfig();
            String projectPath = System.getProperty("user.dir");
            System.out.println(projectPath);
            gc.setOutputDir("C:\\Users\\38492\\Desktop\\guliproject\\guli_parent\\service\\service_edu" + "/src/main/java");
            gc.setAuthor("酷小亚");
            gc.setOpen(false); //生成后是否打开资源管理器
            gc.setFileOverride(false); //重新生成时文件是否覆盖
            /*
             * mp生成service层代码,默认接口名称第一个字母有 I
             * UcenterService
             * */
            gc.setServiceName("%sService"); //去掉Service接口的首字母I
            gc.setIdType(IdType.ID_WORKER); //主键策略
            gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
            gc.setSwagger2(true);//开启Swagger2模式
            mpg.setGlobalConfig(gc);
    // 3、数据源配置
            DataSourceConfig dsc = new DataSourceConfig();
            dsc.setUrl("jdbc:mysql://localhost:3306/guli?serverTimezone=GMT%2B8");
            dsc.setDriverName("com.mysql.cj.jdbc.Driver");
            dsc.setUsername("root");
            dsc.setPassword("123456");
            dsc.setDbType(DbType.MYSQL);
            mpg.setDataSource(dsc);
    // 4、包配置
            PackageConfig pc = new PackageConfig();
            //pc.setModuleName("serviceedu"); //模块名
            pc.setParent("com.jin");
            pc.setController("controller");
            pc.setEntity("entity");
            pc.setService("service");
            pc.setMapper("mapper");
            mpg.setPackageInfo(pc);
    // 5、策略配置
            StrategyConfig strategy = new StrategyConfig();
            strategy.setInclude("edu_subject");
            strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
            strategy.setTablePrefix(pc.getModuleName() + "_"); //生成实体时去掉表前缀
            strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
            strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain =true) setter链式操作
            strategy.setRestControllerStyle(true); //restful api风格控制器
            strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符
            mpg.setStrategy(strategy);
    // 6、执行
            mpg.execute();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68

    注意:表名一定要使用创建的名字

    四、创建监听

    SubjectExcelListener.java

    package com.jin.listener;
    
    import com.alibaba.excel.context.AnalysisContext;
    import com.alibaba.excel.event.AnalysisEventListener;
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.jin.entity.EduSubject;
    import com.jin.entity.excel.SubjectData;
    import com.jin.exceptionhandler.GuliException;
    import com.jin.service.EduSubjectService;
    
    
    public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    
        //因为SubjectExcelListener不能交给spring进行管理,需要自己new,不能注入其他对象
        //不能实现数据库操作
        public EduSubjectService subjectService;
    
        //无参
        public SubjectExcelListener() {
        }
    
        //有参构造
        public SubjectExcelListener(EduSubjectService subjectService) {
            this.subjectService = subjectService;
        }
    
        //读取excel内容,一行一行进行读取
        @Override
        public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
    
            if(subjectData==null){
                throw new GuliException(20001,"文件数据为空");
            }
    
            //一行一行读取,每次读取有两个值;第一个值为一级分类,第二个值为二级分类
            //判断一级分类是否重复
            EduSubject existOneSubject = this.existOneSubject(subjectService, subjectData.getOneSubjectName());
            if(existOneSubject==null){//没用相同一级分类,进行添加
                existOneSubject=new EduSubject();
                existOneSubject.setParentId("0");
                existOneSubject.setTitle(subjectData.getOneSubjectName());//一级分类名称
    
                subjectService.save(existOneSubject);
            }
            //获取一级分类id值
            String pid = existOneSubject.getId();
            //判断二级分类是否重复
            EduSubject existTwoSubject = this.existTwoSubject(subjectService, subjectData.getTwoSubjectName(), pid);
            if(existTwoSubject == null){
                existTwoSubject=new EduSubject();
                existTwoSubject.setParentId(pid);
                existTwoSubject.setTitle(subjectData.getTwoSubjectName());//一级分类名称
    
                subjectService.save(existTwoSubject);
            }
        }
        //判断一级分类不能重复添加
        private EduSubject existOneSubject(EduSubjectService subjectService,String name){
            QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
            wrapper.eq("title",name);
            wrapper.eq("parent_id","0");
            EduSubject oneSubject = subjectService.getOne(wrapper);
            return oneSubject;
        }
    
        //判断二级分类不能重复添加
    
        private EduSubject existTwoSubject(EduSubjectService subjectService,String name,String pid){
            QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
            wrapper.eq("title",name);
            wrapper.eq("parent_id",pid);
            EduSubject TwoSubject = subjectService.getOne(wrapper);
            return TwoSubject;
        }
        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80

    五、编写代码

    1)在持久层中实体类里添加自动填充数据
    在这里插入图片描述

    package com.jin.entity;
    
    import com.baomidou.mybatisplus.annotation.FieldFill;
    import com.baomidou.mybatisplus.annotation.IdType;
    import java.util.Date;
    
    import com.baomidou.mybatisplus.annotation.TableField;
    import com.baomidou.mybatisplus.annotation.TableId;
    import java.io.Serializable;
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    import lombok.Data;
    import lombok.EqualsAndHashCode;
    import lombok.experimental.Accessors;
    
    @Data
    @EqualsAndHashCode(callSuper = false)
    @Accessors(chain = true)
    @ApiModel(value="EduSubject对象", description="课程科目")
    public class EduSubject implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        @ApiModelProperty(value = "课程类别ID")
        @TableId(value = "id",type = IdType.ID_WORKER_STR)
        private String id;
    
        @ApiModelProperty(value = "类别名称")
        private String title;
    
        @ApiModelProperty(value = "父ID")
        private String parentId;
    
        @ApiModelProperty(value = "排序字段")
        private Integer sort;
    
        @ApiModelProperty(value = "创建时间")
        @TableField(fill = FieldFill.INSERT)
        private Date gmtCreate;
    
        @ApiModelProperty(value = "更新时间")
        @TableField(fill = FieldFill.INSERT_UPDATE)
        private Date gmtModified;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    在持久层中创建文件夹excel,类名为SubjectData

    @Data
    public class SubjectData {
    
        //设置excel表头名称
        @ExcelProperty(index=0)
        private String oneSubjectName;
    
        @ExcelProperty(index=1)
        private String twoSubjectName;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    在service接口中添加代码

    public interface EduSubjectService extends IService<EduSubject> {
    
        //添加课程分类
        void saveSubject(MultipartFile file,EduSubjectService subjectService);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在接口实现类中添加代码

    @Service
    public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {
    
        //添加课程分类
        @Override
        public void saveSubject(MultipartFile file,EduSubjectService subjectService) {
    
            try {
                //文件输入流
                InputStream in = file.getInputStream();
                //调用方法进行读取
                EasyExcel.read(in, SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
            }catch (Exception e){
    
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    在业务层controller中添加代码

    package com.jin.controller;
    
    
    import com.jin.R;
    import com.jin.service.EduSubjectService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    
    @RestController
    @RequestMapping("/eduservice/subject")
    @CrossOrigin
    public class EduSubjectController {
    
        @Autowired
        private EduSubjectService subjectService;
    
        //添加课程分类
        //获取上传过来文件,把文件内容读取出来
        @PostMapping("addSubject")
        public R addSubject(MultipartFile file){
            //上传过来excel文件
            subjectService.saveSubject(file,subjectService);
            return R.ok();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    六、效果展示

    本地excel中数据:
    01.xlsx
    在这里插入图片描述

    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述


    声明: 本文章根据视频内容所整理, 视频链接:https://www.bilibili.com/video/BV1dQ4y1A75e?p=97&vd_source=3ad49d22258b09c2fbe8577500597120
  • 相关阅读:
    叠氮聚乙二醇生物素 N3-PEG-Biotin Azide-PEG-Biotin的结构式
    【基于FreeRTOS的STM32F103系统】编写FreeRTOS程序
    Apollo配置中心-手把手教你搭建Apollo配置中心运行环境
    java 企业工程管理系统软件源码 自主研发 工程行业适用
    python 日常处理数据中使用到的零碎知识点(一)
    三个要点,掌握Spring Boot单元测试
    让reviewdog支持gitlab-push-commit,守住代码质量下限
    区块链的生成与基本操作
    【ensp实验】Telnet 协议
    逻辑漏洞基础
  • 原文地址:https://blog.csdn.net/weixin_45737330/article/details/127843768