首先引入hutool-all包和apache.poi包 且poi包需要大于4.1.2
<!-- hutools-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.8</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
核心方法
/**
* 文件名
* @param file
* @return
* @throws Exception
*/
@PostMapping("/upload/excel")
@CrossOrigin
public ApiResult uploadLocal(@RequestPart(value = "file") MultipartFile file) throws Exception {
if (file.isEmpty()) {
ApiResultHandler.buildApiResult(400, "文件不能为空", null);
}
String orgName = file.getOriginalFilename();// 获取文件名
orgName = this.getFileName(orgName);
System.out.println("文件名"+orgName);
try {
ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
// 读取表头 对应实体内部的属性名
reader.addHeaderAlias("问题", "question");
reader.addHeaderAlias("所属科目", "subject");
reader.addHeaderAlias("难度", "level");
reader.addHeaderAlias("选项A", "answerA");
reader.addHeaderAlias("选项B", "answerB");
reader.addHeaderAlias("选项C", "answerC");
reader.addHeaderAlias("选项D", "answerD");
reader.addHeaderAlias("正确答案", "rightAnswer");
reader.addHeaderAlias("题目解析", "analysis");
reader.addHeaderAlias("分数", "score");
List<MultiQuestion> list = reader.readAll(MultiQuestion.class);
AtomicInteger i = new AtomicInteger();
list.forEach(item->{
MultiQuestion multiQuestion = new MultiQuestion();
BeanUtils.copyProperties(item,multiQuestion);
// 执行插入方法
int add = multiQuestionService.add(multiQuestion);
if(add>0){
i.getAndIncrement();
}
});
return ApiResultHandler.buildApiResult(200, "导入成功,共计导入["+i+"]条数据", null);
} catch (Exception e) {
return ApiResultHandler.buildApiResult(400, "导入失败", null);
}
}
对应实体类
package com.exam.entity;
import lombok.Data;
// 选择题实体
@Data
public class MultiQuestion {
// 问题id
private Integer questionId;
//问题
private String question;
// 所属科目
private String subject;
//
private String section;
// 难度 4为易错题
private String level;
// 选项a
private String answerA;
//选项b
private String answerB;
//选项c
private String answerC;
// 选项d
private String answerD;
// 正确答案
private String rightAnswer;
private String analysis; //题目解析
private String imageUrl; //题目图片
// 分数
private Integer score;
}
示例excel
问题 | 所属科目 | 难度 | 选项A | 选项B | 选项C | 选项D | 正确答案 | 题目解析 | 分数 |
test1 | 科目一模拟 | 4 | 这个是正确的 | 这个是错误的 | 这个也是错误的 | 这个还是错误的 | A | 测试数据 | 2 |
test2 | 科目一模拟 | 4 | 这个是正确的 | 这个是错误的 | 这个也是错误的 | 这个还是错误的 | A | 测试数据 | 2 |
test3 | 科目一模拟 | 4 | 这个是正确的 | 这个是错误的 | 这个也是错误的 | 这个还是错误的 | A | 测试数据 | 2 |
test4 | 科目一模拟 | 4 | 这个是正确的 | 这个是错误的 | 这个也是错误的 | 这个还是错误的 | A | 测试数据 | 2 |
test5 | 科目一模拟 | 4 | 这个是正确的 | 这个是错误的 | 这个也是错误的 | 这个还是错误的 | A | 测试数据 | 2 |
test6 | 科目一模拟 | 4 | 这个是正确的 | 这个是错误的 | 这个也是错误的 | 这个还是错误的 | A | 测试数据 | 2 |
test7 | 科目一模拟 | 4 | 这个是正确的 | 这个是错误的 | 这个也是错误的 | 这个还是错误的 | A | 测试数据 | 2 |