基于SpringBoot框架 导入Excel文档
前言:
关于SpringBoot中Excel文档的上传解析
提示:以下是本篇文章正文内容,下面案例可供参考
使用步骤:
1.导入jar包
代码如下(示例):
<!-- xls,xlsx文件 解析jar包 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
2.编写Contriller层
代码如下(示例):
@PostMapping("/importuserinfo")
public CommonResult importUserInfo(@RequestParam("file") MultipartFile file , @RequestParam("schoolId")String schoolId , @RequestParam("areaCode")String areaCode ) {//参数:文件,学校id,地区代码
CommonResult result = new CommonResult();//这个是我自己写的JSON传输对象
Object resultTpye = null;//结果:true,false
String fileName = file.getOriginalFilename();//获取文件名
try {
resultTpye = excelService.importUserInfo(fileName, file, schoolId, areaCode);
} catch (Exception e) {
e.printStackTrace();
}
if(!resultTpye.equals(false) || resultTpye != null){//插入成功
result.setCode(CommonAPI.CODE_200000.getCode());
result.setMessage(CommonAPI.CODE_200000.getMessage());
result.setData(resultTpye);
}else {
result.setCode(CommonAPI.CODE_500012.getCode());
result.setMessage(CommonAPI.CODE_500012.getMessage());
result.setData(resultTpye);
}
return result;
}
3.编写Service业务实现类
代码如下(示例):这边我想导入的是学生信息,信息中包含多张表
/**
* //excel文件解析 学生信息 插入数据库
* @param fileName
* @param file
* @param schoolId
* @param areaCode
* @return
* @throws Exception
*/
@Override
public Object importUserInfo(String fileName, MultipartFile file, String schoolId, String areaCode) throws Exception {
boolean notNull = false;
if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {//判断文件格式
throw new Exception("上传文件格式不正确");
}
boolean isExcel2003 = true;
if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
isExcel2003 = false;
}
InputStream is = file.getInputStream();//文件输入
Workbook wb = null;
if (isExcel2003) {
wb = new HSSFWorkbook(is);
} else {
wb = new XSSFWorkbook(is);
}
Sheet sheet = wb.getSheetAt(0);
if(sheet!=null){
notNull = true;
}
List<User> userList = new ArrayList<User>();//实例化用户对象集合
List<UserStudent> userStudentList = new ArrayList<UserStudent>();//实例化用户学生对象集合
CommonResult memberResultClassInfo = null;//传输对象
ParameterizedTypeReference<CommonResult<Map>> mapTypeRef = new ParameterizedTypeReference<CommonResult<Map>>() {};//传输对象类型
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();//加密对象
User user;//初始化用户对象
UserStudent userStudent;// 初始化用户学生对象、、
Date date = new Date();
Object numClassName = null;//设置一个数用来比较
Object numgreadeCode = null;
//访问数据字典层
Map<String,String> domainMap = (Map<String,String>) redisTemplate.opsForValue().get(CommonAPI.REDIS_EDU_MAP);
if(domainMap == null){
domainMap = restTemplate.getForObject(CommonAPI.SERVER_DATA_DICTIONARY_PATH+"/domain/getservermaininfo",Map.class);
}
//获取文件数据
for (int r = 1; r <= sheet.getLastRowNum(); r++) {
Row row = sheet.getRow(r);
if (row == null){
continue;
}
if( row.getCell(0).getCellType() !=1){//判断字段名
throw new Exception("导入失败(第"+(r+1)+"行,姓名请设为文本格式)");
}
String name = row.getCell(0).getStringCellValue().trim();
if(name == null || name.isEmpty()){//判断字段值
throw new Exception("导入失败(第"+(r+1)+"行,姓名未填写)");
}
name += r;
row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
String phone = row.getCell(1).getStringCellValue().trim();
if(phone==null || phone.isEmpty()){//phone.isEmpty():长度
throw new Exception("导入失败(第"+(r+1)+"行,电话未填写)");
}
String className = row.getCell(2).getStringCellValue().trim();
if(phone==null || phone.isEmpty()){//phone.isEmpty():长度
throw new Exception("导入失败(第"+(r+1)+"行,班级未填写)");
}
String greadeCode = row.getCell(3).getStringCellValue().trim();
if(phone==null || phone.isEmpty()){//phone.isEmpty():长度
throw new Exception("导入失败(第"+(r+1)+"行,年级未填写)");
}
String userSex = row.getCell(4).getStringCellValue().trim();
if(userSex==null || userSex.isEmpty()){
throw new Exception("导入失败(第"+(r+1)+"行,性别未填写)");
}
String eduCode = row.getCell(5).getStringCellValue().trim();
if(eduCode==null || eduCode.isEmpty()){
throw new Exception("导入失败(第"+(r+1)+"行,学级代码未填写)");
}
String loginID;
if(row.getCell(6) == null){
loginID = "0";
}else{
loginID = row.getCell(6).getStringCellValue();
}
userStudent = new UserStudent();//实例化
user = new User();//实例化用户对象
Map<String,Object> classInfoMap = new HashMap<>();//实例化班级信息map对象
//给用户对象赋值
user.setUserName(name);
user.setPhoneNumber(phone);//将值放入用户对象中
Integer userSexInt = userSex.equals("男") ? 1 : 0;
user.setUserSex(userSexInt);
user.setSchoolId(schoolId);
user.setPassword(bCryptPasswordEncoder.encode(CommonAPI.DEFAULT_PASSWORD));//SpringBoot 自带的 MD5加密
user.setLoginID(loginID);
userList.add(user);//加入到用户集合中
//将班级信息添加到集合中 准备发送
classInfoMap.put("className",className);
classInfoMap.put("greadeCode",greadeCode);
classInfoMap.put("schoolId",schoolId);
if(numClassName != className || numgreadeCode != greadeCode ){//班级名不同 或者 年级代码不同 的时候
//将数据发送到school工程中的class控制层()
memberResultClassInfo = restTemplate.exchange(domainMap.get("zhihuiketang-school")+"/school/class/importexcelclassinfo", HttpMethod.POST,
new HttpEntity<>(classInfoMap),mapTypeRef).getBody();//发送参数
}
Map<String,Object> classIdMap = (HashMap) memberResultClassInfo.getData();
Integer classId = (Integer) classIdMap.get("classId");//取出班级id
numClassName = className;//赋值
numgreadeCode = greadeCode;
//给用户学生对象赋值
userStudent.setMtEduCode(eduCode);
userStudent.setClassId(classId);
userStudentList.add(userStudent);//加入到用户学生集合中
if(userList.size() % 400 == 0 || r == userList.size() -1){//每100次调用
System.out.println("第:"+r+":次");
studentService.getSudentExcelInfoList(userList,areaCode,userStudentList);
}
}
// studentService.getSudentExcelInfoList(userList,areaCode,userStudentList);
System.out.println("开始时间:"+date);
System.out.println("结束时间:"+new Date());
return notNull;
}
studentService 代码如下(示例):
@Transactional(propagation = Propagation.REQUIRES_NEW)
@Override
public void getSudentExcelInfoList(List<User> userList, String areaCode, List<UserStudent> userStudentList) {
SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH,false);
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
UserStudentMapper userStudentMapper = sqlSession.getMapper(UserStudentMapper.class);
// 插入数据
for (int i = 0; i < userList.size(); i++) {
User userResord = userList.get(i);//获取到每一个学生对象
if(userResord.getLoginID().equals("0") || "".equals(userResord.getLoginID()) ){//登录账号为空时
userMapper.insertExcelUser(userResord);//添加学生信息
//生成用户账号
String loginId = StringUtil.generateLoginID(areaCode, userResord.getId());
userMapper.updateUserLoginID(userResord.getId(),loginId);
UserStudent userStudent = userStudentList.get(i);//获取到每一个用户学生对象
//先在用户学生表中查询班级id是否存在
UserStudent userStudentId = userStudentMapper.selectUserStudentByClassId(userStudent.getClassId(),userResord.getId());
if(userStudentId == null){
//为空则添加用户学生信息 TODO---------学级代码以后可能会修改--------------
userStudentMapper.insertExcelUserStudent(userResord.getId(),userStudent.getClassId(),userStudent.getMtEduCode());
}
}else {
userMapper.updateExcelUser(userResord);//修改学生信息
}
}
sqlSession.commit();
sqlSession.clearCache();
}catch (Exception e){
sqlSession.rollback();
}finally {
sqlSession.close();
}
}
效果:
总结:
以上就是今天要讲的内容,本文仅仅简单介绍了Excel导入案例,具体的需求需要你们自己摸索哈 (非原创我也是看某位大佬的帖子摸索出来的,只是忘记那篇帖子的链接了)(基于SpringBoot框架 导入Excel文档)