使用EasyExcel从文件读取数据存储到数据库中

1.在pom.xml中引入poi和EasyExcel的依赖

简单读写和依赖的代码

2.使用代码生成器在各层中生成subject的内容

使用代码生成器生成subject的mapper controller service entity
注:把代码生成器中的策略配置部分 strategy.setInclude(“edu_subject”) 这一句应该对应想要操作的表
要生成subject的各层内容 对应的就是edu_subject这张表

// 5、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("edu_subject");

3.创建上传的文件对应的实体类

注:和数据库表对应的实体类区分

package com.kaki.serviceedu.entity.excel;

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;

/**
 * 创建课程excel文件对应的实体类
 */

@Data
public class SubjectData {
   
    @ExcelProperty(index = 0)//index表示对应excel文件的第一列
    private String oneSubjectName;
    @ExcelProperty(index = 1)//对应excel文件的第二列
    private String twoSubjectName;
}

4.controller

package com.kaki.serviceedu.controller;


import com.kaki.commonutils.R;
import com.kaki.serviceedu.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;

/**
 *
 * @author kaki
 * @since 2021-02-28
 */
@RestController
@RequestMapping("/serviceedu/subject")
@CrossOrigin
public class EduSubjectController {
   

    @Autowired
    private EduSubjectService subjectService;

   
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用EasyExcel提供的读取Excel文件数据的功能,将数据读取到Java程序,然后再使用JDBC将数据插入到数据库。 以下是一个示例代码,演示如何使用EasyExcelExcel文件的数据导入到MySQL数据库: ```java // 读取Excel文件数据 String fileName = "example.xlsx"; List<DemoData> dataList = new ArrayList<>(); EasyExcel.read(fileName, DemoData.class, new DemoDataListener(dataList)).sheet().doRead(); // 将数据插入到数据库 String url = "jdbc:mysql://localhost:3306/test?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"; String username = "root"; String password = "password"; String sql = "INSERT INTO demo_data (id, name, age) VALUES (?, ?, ?)"; try (Connection conn = DriverManager.getConnection(url, username, password); PreparedStatement pstmt = conn.prepareStatement(sql)) { for (DemoData data : dataList) { pstmt.setInt(1, data.getId()); pstmt.setString(2, data.getName()); pstmt.setInt(3, data.getAge()); pstmt.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } ``` 其,`DemoData`是一个Java类,用于存储Excel文件的数据。`DemoDataListener`是一个实现了EasyExcel监听器接口的类,用于处理读取Excel文件时的事件。在`DemoDataListener`的`invoke`方法,将读取到的数据存储到`dataList`。 在上述代码使用JDBC连接MySQL数据库,并将数据插入到`demo_data`表。你需要根据自己的实际情况修改数据库连接信息和SQL语句。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值