Skip to content

之前导出Excel可以直接模拟数据,但是读取Excel存储数据库和直接读取操作有点不同,因为涉及到了大文件读取,因此写入数据一般是分批写入的,因此我们使用MybatisPlus来链接数据库

创建数据库

sql
CREATE TABLE `demo` (
  `title` varchar(255) DEFAULT NULL COMMENT '标题',
  `date` datetime DEFAULT NULL COMMENT '日期',
  `double_data` double(10,2) DEFAULT NULL COMMENT '数字标题',
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

引入数据库依赖

xml
<!--mybatis-plus-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.3.1</version>
</dependency>

<!--Mysql依赖包-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

配置文件

yaml
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/你的数据库名字?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowMultiQueries=true&rewriteBatchedStatements=true
    username: root
    password: root

mybatis-plus:
  type-aliases-package: com.xk857
  global-config:
    banner: false
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 开启日志

创建对象实体类

java
@Data
@TableName("demo")
public class DemoData {

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    @ExcelProperty("字符串标题")
    private String title;

    @ExcelProperty("日期标题")
    private Date date;

    @ExcelProperty("数字标题")
    private Double doubleData;
}

创建Dao层

java
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xk857.excel.domain.DemoData;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface DemoMapper extends BaseMapper<DemoData> {
}

创建Service层

java
import com.baomidou.mybatisplus.extension.service.IService;
import com.xk857.excel.domain.DemoData;

public interface IDemoService extends IService<DemoData> {
}
java
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xk857.excel.dao.DemoMapper;
import com.xk857.excel.domain.DemoData;
import com.xk857.excel.service.IDemoService;
import org.springframework.stereotype.Service;

@Service
public class DemoServiceImpl  extends ServiceImpl<DemoMapper, DemoData> implements IDemoService {
}