1.首先先创建一个spring boot项目在pom文件中导入依赖
<?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.6.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>excelTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>excelTest</name>
<description>excelTest</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--日期格式化工具-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.1</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.1.4</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.4.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.5.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>5.6.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.配置数据库文件和mybatis-plus文件
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/你的数据库名称?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
mybatis-plus:
mapper-locations: classpath*:/mapper/*.xml
global-config:
db-config:
logic-not-delete-value: N
logic-delete-value: Y
id-type: auto
3.创建好springMvc需要的包
4.创建一张简单的表
DROP TABLE IF EXISTS student;
CREATE TABLE student(
id INT NOT NULL AUTO_INCREMENT COMMENT 'id' ,
created_by VARCHAR(32) COMMENT '创建人' ,
created_time VARCHAR(32) COMMENT '创建时间' ,
updated_by VARCHAR(32) COMMENT '更新人' ,
updated_time VARCHAR(32) COMMENT '更新时间' ,
name VARCHAR(255) COMMENT '姓名' ,
age VARCHAR(255) COMMENT '年龄' ,
sex VARCHAR(255) COMMENT '性别' ,
PRIMARY KEY (id)
) COMMENT = '学生表';
5.创建一个跟数据库对应的excle文件(由于放不了附件,大家自己去创建吧)
6.创建实体类(强烈建议使用lombok插件)
package com.li.pojo;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
* 学生表
* @author admin
*/
@Data
@TableName("这里填你自己生成的表")
public class Student {
private Integer id;
private String name;
private String age;
private String sex;
}
7.创建service和serviceimpl(如果使用了mybatis-plus需要继承IService<Student>)
package com.li.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.li.pojo.Student;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* @author admin
*/
public interface StudentService extends IService<Student> {
/**
* 添加学生信息到数据库
* @return
*/
boolean saveBathStudent();
/**
* 从数据库导出文件
* @return
*/
boolean exportExcle() throws IOException;
}
实现类也一样
8.创建mapper.xml
package com.li.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.li.pojo.Student;
import org.apache.ibatis.annotations.Mapper;
/**
* 学生表mapper
* @author admin
*/
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
}
9.这些准备工作做好之后,就可以开始编写代码了
首先在service中写一个插入和导出的方法
/**
* 添加学生信息到数据库
* @return
*/
boolean saveBathStudent();
/**
* 从数据库导出文件
* @return
*/
boolean exportExcle() throws IOException;
10.我们先从插入方法开始
上面我们创建了一个接口,接下来我们来实现他
@Override
public boolean saveBathStudent() {
//创建一个List用来存实体类
List<Student> studentList = new ArrayList();
//使用hutool工具包的Excel读取文件,03读取的是xls,07读取的是xlsx Excel03SaxReader Excel07axReader
Excel03SaxReader excel03SaxReader = new Excel03SaxReader(createRowHandler(studentList));
//hutool工具包会自动读取里面的文件
excel03SaxReader.read(PATH,0);
//因为下面的方法我是80条插入一次,所以可能会有遗漏,所以这里调用一下mybatis-plus批量保存方法,防止遗漏
if (studentList.size()>0){
this.saveBatch(studentList);
}
return true;
}
private RowHandler createRowHandler(List<Student> studentList) {
return new RowHandler() {
/**
*
* @param sheetIndex sheet页,0开始
* @param rowIndex 行数
* @param rowList excle内容数据
*/
@Override
public void handle(int sheetIndex, int rowIndex, List<Object> rowList) {
Student student = new Student();
//这里我是从第二行开始,所以是>=1
if (rowIndex>=1){
student.setName(String.valueOf(rowList.get(0)));
student.setAge(String.valueOf(rowList.get(1)));
student.setSex(String.valueOf(rowList.get(2)));
studentList.add(student);
//防止溢出,80条插入一次
if (studentList.size()>=80){
insertStudentBatch(studentList);
studentList.clear();
}
}
}
};
}
//因为在createRowHandler方法中不能内部实现批量保存方法,所以需要单独写一个方法出来,然后在方法中调用
public void insertStudentBatch(List<Student> studentList){
this.saveBatch(studentList);
}
这样一个插入的方法就写好了,接下来我们测试一下,创建一个StudentController,这里为了方便,我把导入和导出的方法一起发出来
package com.li.controller;
import com.li.service.StudentService;
import com.li.utils.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.io.IOException;
/**
* @author admin
*/
@RestController
@RequestMapping("/excle")
public class StudentController {
@Resource
private StudentService studentService;
/**
* 导入
*/
@PostMapping("/excleImport")
public R excleImport(){
return R.ok(studentService.saveBathStudent());
}
@PostMapping("/exportEecle")
/**
* 导出
*/
public R exportEecle() throws IOException {
return R.ok(studentService.exportExcle());
}
}
接下来让我们来看一下测试结果
postman:
数据库:
以上就是导入的结果,接下来我们把数据库里面的数据导出
实现导出方法
@Override
public boolean exportExcle() throws IOException {
//调用mybatis-plus中的list方法查询数据库中的所有数据
List<Student> list = this.list();
//创建一个03的excle
Workbook workbook = new HSSFWorkbook();
//创建一页sheet
Sheet sheetAt = workbook.createSheet("BC24R");
//创建行
Row row = sheetAt.createRow(0);
//创建列
Cell cell = row.createCell(0);
cell.setCellValue("姓名");
Cell cell1 = row.createCell(1);
cell1.setCellValue("年龄");
Cell cell2 = row.createCell(2);
cell2.setCellValue("性别");
//根据数据库查询出的所有数据长度来进行输出到excle表中
for (int i = 0; i < list.size(); i++) {
Row row1 = sheetAt.createRow(i + 1);
Cell cell3 = row1.createCell(0);
cell3.setCellValue(list.get(i).getName());
Cell cell4 = row1.createCell(1);
cell4.setCellValue(list.get(i).getAge());
Cell cell5 = row1.createCell(2);
cell5.setCellValue(list.get(i).getSex());
}
//输出
FileOutputStream fileOutputStream = new FileOutputStream("F:\\02.xls");
workbook.write(fileOutputStream);
fileOutputStream.close();
return true;
}
以上就是导出方法,接下来我们看看结果
输出到了我们指定的盘符中并且数据也全部输出完毕
小结:
以上就是我用srping boot,mybatis-plus,hutool工具包做出来的excle文件导入导出的一个小demo,如果还有哪里不清晰或有疑问的地方,欢迎大家在评论区讨论