springBoot项目中excel表的导入
最近写了一个关于学生信息excel表导入到数据库的接口,记录一下加强记忆理解,也为以后容易复用
导入的思路就是前端导入excel表,后端用MultipartFile接收到,拿到文件流后,用导入的那一套操作将流中的数据取出来放到List中(其他形式接收应该也可以,看业务需求),然后再将得到的List做保存到数据库中,导入完成。
下面是具体实现
- 导入的excel表格的样式是这样的:
- 第一步导入相关的jar包(j具体包应该用不了这么多,但是导进去也无妨,有些包和导出有关系):
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
<exclusions>
<exclusion>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.1</version>
</dependency>
- 第二步:controller层写接口:
/***
* 导入excel,新增学生
**/
@ApiOperation(value = "导入excel,新增学生")
@PostMapping("/importExcel")
public ResponseMessage exportExcel (@RequestParam(value = "file", required = true) MultipartFile file)throws Exception {
//获取文件名
String fileName = file.getOriginalFilename();
//获取输入流
InputStream inputStream = file.getInputStream();
List<Map<String,String>> mapList = excelService.importExcel(inputStream, fileName);
studentService.saveStudent(mapList);
return Result.success();
}
- 第三步:核心实现service,这一步改掉了,在这里就不删了
package com.jero.combined.server.modules.user.service.impl;
import com.jero.combined.server.modules.user.entity.StudentEO;
import com.jero.common.exception.JeroBaseException;
import com.jero.common.utils.StringUtils;