SpringBoot提供接口实现Excel导入数据并存储到数据库中

完整项目文件

1 效果展示

1.1 Excel数据

zxy.xlsx

1.2 导入后数据库中数据

CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',`name` varchar(255) DEFAULT NULL COMMENT '姓名',`phone` varchar(255) DEFAULT NULL COMMENT '联系方式',`address` varchar(255) DEFAULT NULL COMMENT '联系地址',`birthday` datetime DEFAULT NULL COMMENT '出生日期',`des` varchar(255) DEFAULT NULL COMMENT '自我描述',PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

2 代码开发

2.1 Pojo

根据excel数据需求,设计数据库表结构,并开发实体类代码

public class User implements Serializable {private Integer id;private String name;private String phone;private String address;private Date birthday;private String des;private static final long serialVersionUID = 1L;public User(Integer id, String name, String phone, String address, Date birthday, String des) {this.id = id;this.name = name;this.phone = phone;this.address = address;this.birthday = birthday;this.des = des;}public User() {super();}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name == null ? null : name.trim();}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone == null ? null : phone.trim();}public String getAddress() {return address;}public void setAddress(String address) {this.address = address == null ? null : address.trim();}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String getDes() {return des;}public void setDes(String des) {this.des = des == null ? null : des.trim();}@Overridepublic boolean equals(Object that) {if (this == that) {return true;}if (that == null) {return false;}if (getClass() != that.getClass()) {return false;}User other = (User) that;return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))&& (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName()))&& (this.getPhone() == null ? other.getPhone() == null : this.getPhone().equals(other.getPhone()))&& (this.getAddress() == null ? other.getAddress() == null : this.getAddress().equals(other.getAddress()))&& (this.getBirthday() == null ? other.getBirthday() == null : this.getBirthday().equals(other.getBirthday()))&& (this.getDes() == null ? other.getDes() == null : this.getDes().equals(other.getDes()));}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + ((getId() == null) ? 0 : getId().hashCode());result = prime * result + ((getName() == null) ? 0 : getName().hashCode());result = prime * result + ((getPhone() == null) ? 0 : getPhone().hashCode());result = prime * result + ((getAddress() == null) ? 0 : getAddress().hashCode());result = prime * result + ((getBirthday() == null) ? 0 : getBirthday().hashCode());result = prime * result + ((getDes() == null) ? 0 : getDes().hashCode());return result;}
}

2.2 Controller

首先看controller层,这里是为外部提供一个访问接口,通过/excel/import路径访问。因为使用的POST请求方式,所以在请求的时候需要将file文件一同传入。然后获取file文件的文件名,用于后续判断他是不是一个excel文件。继续就是哟个了Service的batchImport方法进行业务逻辑处理。

@RestController
@RequestMapping("/excel/")
public class TestController {@Autowiredprivate ImportExcelService importExcelService;@PostMapping("/import")public boolean addUser(@RequestParam("file") MultipartFile file) {boolean a = false;String fileName = file.getOriginalFilename();try {a = importExcelService.batchImport(fileName, file);} catch (Exception e) {e.printStackTrace();}return  a;}}

2.3 Service

在Service层,首先设计一个interface接口,然后定义一个方法

public interface ImportExcelService {boolean batchImport(String fileName, MultipartFile file) throws Exception;}

ImportExcelServiceImpl 主要是对整个需求的逻辑进行开发,从controller处获得文件名称和文件。那么拿到这些信息后,我们首先要判断,这是不是一个excel文件,按照excel的扩展名来说有xls和xlsx两种,要使用不同的函数处理。其次,一个excel是可以有很多的sheet页的,需要使用getSheetAt获取你需要的sheet页或者依次获得sheet页。最后就是获取每个sheet页中的行数据和单元格ceil数据。使用mapper层定义的三个方法,使用selectByName()方法判断对应的姓名是否存在,存在即更新,不存在即删除。


@Service
@Transactional(readOnly = true)
public class ImportExcelServiceImpl implements ImportExcelService {@Autowiredprivate UserMapper userMapper;/*** 首先判断文件扩展名* 其次获取不同sheet页的内容* 然后获取行数据* 最后获取单元格数据*/@Transactional(readOnly = false,rollbackFor = Exception.class)@Overridepublic boolean batchImport(String fileName, MultipartFile file) throws Exception {boolean notNull = false;List<User> userList = new ArrayList<User>();if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {throw new MyException("上传文件格式不正确");}boolean isExcel2003 = true;if (fileName.matches("^.+\\.(?i)(xlsx)$")) {isExcel2003 = false;}InputStream is = file.getInputStream();Workbook wb = null;/*** Excel2003以前的版本,扩展名是.xls,使用HSSFWorkbook()* Excel2007之后的版本,扩展名是.xlsx,使用XSSFWorkbook()*/if (isExcel2003) {wb = new HSSFWorkbook(is);} else {wb = new XSSFWorkbook(is);}// 获取excel的第一个sheet页Sheet sheet = wb.getSheetAt(0);if(sheet!=null){notNull = true;}User user;// 循环行数for (int r = 1; r <= sheet.getLastRowNum(); r++) {// 获取sheet的第r行的数据Row row = sheet.getRow(r);if (row == null){continue;}user = new User();/*** int CELL_TYPE_NUMERIC = 0;* int CELL_TYPE_STRING = 1;* int CELL_TYPE_FORMULA = 2;* int CELL_TYPE_BLANK = 3;* int CELL_TYPE_BOOLEAN = 4;* int CELL_TYPE_ERROR = 5;*/if( row.getCell(0).getCellType() !=1){throw new MyException("导入失败(第"+(r+1)+"行,姓名请设为文本格式)");}String name = row.getCell(0).getStringCellValue();if(name == null || name.isEmpty()){throw new MyException("导入失败(第"+(r+1)+"行,姓名未填写)");}row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);String phone = row.getCell(1).getStringCellValue();if(phone==null || phone.isEmpty()){throw new MyException("导入失败(第"+(r+1)+"行,电话未填写)");}String add = row.getCell(2).getStringCellValue();if(add==null){throw new MyException("导入失败(第"+(r+1)+"行,不存在此单位或单位未填写)");}Date date;if(row.getCell(3).getCellType() !=0){throw new MyException("导入失败(第"+(r+1)+"行,入职日期格式不正确或未填写)");}else{date = row.getCell(3).getDateCellValue();}String des = row.getCell(4).getStringCellValue();user.setName(name);user.setPhone(phone);user.setAddress(add);user.setBirthday(date);user.setDes(des);userList.add(user);}for (User userResord : userList) {//首先判断该姓名是否已经存在String name = userResord.getName();int cnt = userMapper.selectByName(name);if (cnt == 0) {//不存在即插入userMapper.addUser(userResord);System.out.println(" 插入 "+userResord);} else {//存在即更新userMapper.updateUserByName(userResord);System.out.println(" 更新 "+userResord);}}return notNull;}
}

2.4 Mapper

定义三个函数,用于判断用户是否存在,进行更新和插入

@Mapper
public interface UserMapper {// 当查到数据库中没有对应姓名记录时,插入void addUser(User sysUser);// 当数据库中有对应姓名记录时,更新int updateUserByName(User sysUser);// 判断是都存在对应的姓名记录int selectByName(String name);
}

根据mapper定义的函数,在UserMapper.xml文件中写SQL

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zxy.ImportExcelProject.mapper.UserMapper"><resultMap id="BaseResultMap" type="com.zxy.ImportExcelProject.pojo.User"><constructor><idArg column="t_id" javaType="java.lang.Integer" jdbcType="INTEGER" /><arg column="t_name" javaType="java.lang.String" jdbcType="VARCHAR" /><arg column="t_phone" javaType="java.lang.String" jdbcType="VARCHAR" /><arg column="t_address" javaType="java.lang.String" jdbcType="VARCHAR" /><arg column="t_birthday" javaType="java.util.Date" jdbcType="TIMESTAMP" /><arg column="t_des" javaType="java.lang.String" jdbcType="VARCHAR" /></constructor></resultMap><insert id="addUser" parameterType="com.zxy.ImportExcelProject.pojo.User">insert into user(name,phone,address,birthday,des)values(#{name},#{phone},#{address},#{birthday},#{des})</insert><update id="updateUserByName" parameterType="com.zxy.ImportExcelProject.pojo.User">update usersetphone=#{phone},address=#{address},birthday=#{birthday},des=#{des}where name = #{name}</update><select id="selectByName" resultType="java.lang.Integer">SELECTcount(*)FROM userWHERE name=#{name}</select>
</mapper>

3 接口测试

SpringBoot提供接口实现Excel导入数据并存储到数据库中相关推荐

  1. 如何用DELPHI实现把WORD、EXCEL和图片等存储到数据库中

    如何用DELPHI实现把WORD.EXCEL和图片等存储到数据库中 用image字段保存这些文档.     var         word_stream:   TMemoryStream;      ...

  2. excel查询mysql数据库表,excel创建数据表/查询mysql数据库中所有表名

    excel两个表格,数据库表与专门查询该数据库信息的表.在查询表中以多个项目进行查询符合条件的数据. 可以用"筛选"这个功能,在菜单里,对两个列进行筛选,符合条件的就会显示出来.很 ...

  3. Excel导入数据,未在本地计算机上注册“Microsoft.Jet.OLEDB.4.0”提供程序

    Excel导入数据,未在本地计算机上注册"Microsoft.Jet.OLEDB.4.0"提供程序: .NET在导入Excel时,使用了一个Microsoft.Jet.OLEDB. ...

  4. excel导入数据校验_从Excel数据验证列表中选择多个项目

    excel导入数据校验 You've probably used an Excel data validation drop down list, where you can click the ar ...

  5. excel导入数据校验_Excel数据验证更新

    excel导入数据校验 I've finally updated my Data Validation intro video, so it shows the steps for creating ...

  6. excel导入数据校验_使用Excel数据验证限制日期范围

    excel导入数据校验 Yesterday, one of my clients emailed to let me know that she was having trouble entering ...

  7. excel导入数据校验_Excel数据验证错误消息

    excel导入数据校验 Do you like to use error checking in Excel, so that problem cells are flagged, or do you ...

  8. SpringBoot集成EasyPoi实现Excel导入导出

    作者介绍: 本人Java特工,代号:Cris Li : 中文名:克瑞斯理 简书地址: 消失的码农 - 简书 CSDN地址: https://blog.csdn.net/jianli95 个人纯洁版博客 ...

  9. 使用Echarts制作散点图(Excel导入数据方式)

    2019独角兽企业重金招聘Python工程师标准>>> Echarts相当于一款JS插件,可以制作出绚丽多彩的图表,其支持制作的图表类型和可以使用的样式都非常丰富.本文以Echart ...

最新文章

  1. Handler消息机制(九):IntentService源码解析
  2. 洛谷 - P4009 汽车加油行驶问题(分层图最短路/最小费用最大流)
  3. python中的常量_Python中的变量和常量
  4. linux 分区 文件,Linux的分区与文件结构
  5. Evaluation or Assessment
  6. 如何做实时监控?—— 参考 Spring Boot 实现
  7. 【Linux】自主实现my_sleep【转】
  8. 20多岁的一无所有,其实是理所应当的
  9. 上班两年干了些啥?该思考人生
  10. HDB3码编码C语言实现
  11. 软件测试电脑功率,姗姗来迟的测试——功率计实测电脑耗电情况之三【i3 2100 + H61 配置篇】...
  12. python3 获取电脑上某个点的颜色RGB值
  13. 在上海创业的日子之注册公司的详细流程
  14. 用adb shell让APP获得Root权限 by SuperSU
  15. 【redis源码】删除大key导致redis主从切换
  16. java graphics2d旋转_反向Java Graphics2D缩放和旋转坐标
  17. Java基于springboot +vue网上超市购物网站 多商家
  18. Kotlin 从入门到实战(一)
  19. python语言编程函数_Python编程语言的函数功能
  20. 文本聚类平移算法的几点问题

热门文章

  1. python在一个画布上画多个子图
  2. 上Github,北大、清华、浙大、中科大4大名校课程在线学,加星总数超1.8万
  3. android百度地图overlay卡顿,百度地图maker过多,导致卡顿的优化
  4. 生鲜电商的下半场,叮咚买菜还有多少故事能讲?
  5. Selenium-WebDriver的运行原理
  6. python之判断类型
  7. 自动化运维工具——puppet详解(一)
  8. win32com-python操作Excel
  9. MySQL缓冲区内存不足问题
  10. 师范专业如何计算机,师范类计算机科学与技术就业前景如何?毕业后做信息老师么?...