springboot excel数据批量导入

1、pom.xml 引入poi依赖

<!--poi--><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.0</version></dependency>

2、controller 方法

 /*** 批量导入学生* @param file  文件* @param request* @return* @throws Exception*/
@Transactional
@RequestMapping("/importStu")
public ApiJsonRes importStu(MultipartFile file, HttpServletRequest request) throws Exception{//响应数据ApiJsonRes apiJsonRes=new ApiJsonRes("201","导入失败");if(file == null){apiJsonRes.setApiResCodeDesc("导入文件不能为空");return apiJsonRes;}//读取文件流InputStream is = file.getInputStream();//文件名String fileName=file.getOriginalFilename();boolean notNull = false;if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {apiJsonRes.setApiResCodeDesc("上传文件格式不正确");return apiJsonRes;}Workbook wb = null;if (fileName.matches("^.+\\.(?i)(xlsx)$")) {//xlsx格式wb = new XSSFWorkbook(is);} else {//xls格式wb = new HSSFWorkbook(is);}if (wb != null) {//默认读取第一个sheetSheet sheet = wb.getSheetAt(0);if (sheet != null) {//最先读取首行boolean firstRow = true;List<Student> studentList = new ArrayList<>();boolean isThrow = false;/*根据手机号判断文件是否包含重复的学生,如果需要多个字段唯一确定一条数据可以使用List<Map<String, Object>>,下面同样使用contains判断是否已经包含同一条数据*/List<String> phoneList=new ArrayList<>();try {if (sheet.getLastRowNum() > 0) {for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {//循环行Student student = new Student();Row row = sheet.getRow(i);//首行  提取注解if (firstRow) {if (row.getCell(0).getStringCellValue().equals("姓名")&& row.getCell(2).getStringCellValue().equals("性别")&& row.getCell(3).getStringCellValue().equals("手机号")&& row.getCell(5).getStringCellValue().equals("年级班级")) {} else { apiJsonRes.setApiResCodeDesc("格式不正确,请下载模板进行参考");return apiJsonRes;}firstRow = false;} else {//忽略空白行if (row == null || ToolHelp.isRowEmpty(row)) {continue;}int theRow = i + 1;if (row.getCell(0) != null) {row.getCell(0).setCellType(CellType.STRING);String stuName = row.getCell(0).getStringCellValue();if (StringUtils.isEmpty(stuName)) {isThrow = true;apiJsonRes.setApiResCodeDesc("导入失败(第" + theRow + "行,姓名不能为空)");throw new RuntimeException("导入失败(第" + theRow + "行,姓名不能为空)");} else {student.setName(stuName);}} else {isThrow = true;apiJsonRes.setApiResCodeDesc("导入失败(第" + theRow + "行,学员姓名不能为空)");throw new RuntimeException("导入失败(第" + theRow + "行,学员姓名不能为空)");}if (row.getCell(1) != null) {row.getCell(1).setCellType(CellType.STRING);String stuSex = row.getCell(1).getStringCellValue();if (StringUtils.isEmpty(stuSex)) {isThrow = true;apiJsonRes.setApiResCodeDesc("导入失败(第" + theRow + "行,性别不能为空)");throw new RuntimeException("导入失败(第" + theRow + "行,性别不能为空)");} else {int sex = 1;if (stuSex.equals("女")) {sex = 2;}student.setSex(sex);}} else {isThrow = true;apiJsonRes.setApiResCodeDesc("导入失败(第" + theRow + "行,性别不能为空)");throw new RuntimeException("导入失败(第" + theRow + "行,性别不能为空)");}if (row.getCell(2) != null) {row.getCell(2).setCellType(CellType.STRING);String stuPhone = row.getCell(2).getStringCellValue();if (StringUtils.isEmpty(stuPhone) || stuPhone.length() != 11) {isThrow = true;apiJsonRes.setApiResCodeDesc("导入失败(第" + theRow + "行,手机号有误)");throw new RuntimeException("导入失败(第" + theRow + "行,手机号有误)");} else {if (!phoneList.isEmpty() && phoneList.size() > 0) {//判断手机号是否重复if (phoneList.contains(stuPhone)) {isThrow = true;apiJsonRes.setApiResCodeDesc("导入失败(第" + theRow + "行,手机号" + stuPhone + "有重复)");throw new RuntimeException("导入失败(第" + theRow + "行,手机号" + stuPhone + "有重复)");} else {phoneList.add(stuPhone);student.setPhone(stuPhone);}} else {student.setPhone(stuPhone);}}} else {isThrow = true;apiJsonRes.setApiResCodeDesc("导入失败(第" + theRow + "行,手机号有误)");throw new RuntimeException("导入失败(第" + theRow + "行,手机号有误)");}if (row.getCell(3) != null) {row.getCell(3).setCellType(CellType.STRING);String stuGrade = row.getCell(3).getStringCellValue();if (StringUtils.isEmpty(stuGrade)) {isThrow = true;apiJsonRes.setApiResCodeDesc("导入失败(第" + theRow + "行,年级班级不能为空)");throw new RuntimeException("导入失败(第" + theRow + "行,年级班级不能为空)");} else {student.setGrade(stuGrade);}} else {isThrow = true;apiJsonRes.setApiResCodeDesc("导入失败(第" + theRow + "行,年级班级不能为空)");throw new RuntimeException("导入失败(第" + theRow + "行,年级班级不能为空)");}student.setCreateTime(new Date());studentList.add(student);}if (isThrow) {break;}}} else {isThrow = true;apiJsonRes.setApiResCodeDesc("导入失败,数据为空");throw new RuntimeException("导入失败,数据为空");}}catch (Exception e) {e.printStackTrace();}if (isThrow) {return apiJsonRes;} else {if(!studentList.isEmpty() && studentList.size() > 0){int addRes=studentService.addList(studentList);if(addRes > 0){apiJsonRes.setApiResCode("200");apiJsonRes.setApiResCodeDesc("导入成功");}}else{return apiJsonRes;}}} else {apiJsonRes.setApiResCodeDesc("导入失败,数据为空");}} else {apiJsonRes.setApiResCodeDesc("导入失败,数据为空");}return apiJsonRes;
}
判断空行
public static boolean isRowEmpty(Row row) {for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {Cell cell = row.getCell(c);if (cell != null && cell.getCellType() != CellType.BLANK)return false;}return true;
}
时间处理
//excel中的数据格式必须是yyyy-MM-dd(如:2020-10-12)
if (row.getCell(4) != null) {row.getCell(4).setCellType(CellType.STRING);String sTime = row.getCell(4).getStringCellValue();if (StringUtils.isEmpty(sTime)) {isThrow = true;apiJsonRes.setApiResCodeDesc("导入失败(第" + theRow + "行,时间不能为空)");throw new RuntimeException("导入失败(第" + theRow + "行,时间不能为空)");} else {Date s=TimeHelp.stringToDate("yyyy-MM-dd",sTime);enroll.setCourseStartTime(s);}
} else {isThrow = true;apiJsonRes.setApiResCodeDesc("导入失败(第" + theRow + "行,时间不能为空)");throw new RuntimeException("导入失败(第" + theRow + "行,时间不能为空)");
}
string 类型日期转Date
/*** string 类型日期转Date* @param patterm string 格式* @param str 时间* @return* @throws ParseException*/
public static Date stringToDate(String patterm,String str) throws ParseException {DateFormat format1 = new SimpleDateFormat(patterm);Date date = null;date = format1.parse(str);return date;
}
捕获异常
 /*注意:手动抛出异常,放在try ...里才会执行接下来的代码throw new RuntimeException("导入失败,数据为空");try catch嵌套:内层不能捕获时,会考虑外层内否捕获,内层能捕获,则外层catch不执行。
*/
catch (ParseException e){e.printStackTrace();apiJsonRes.setApiResCodeDesc("导入失败(第" + theRow + "行,请核对日期)");isThrow=true;//用于之后的逻辑处理
}catch (Exception e) {e.printStackTrace();
}

3、service

//service层就不再贴代码了

4、mybatis(StudentMapper.xml)

<!--1.批量添加-->
<insert id="addList" parameterType="com.pojo.Student">insert into student (id, name,grade, phone,sex)values<foreach collection="studentList" separator="," index="index" item="item">(#{item.id,jdbcType=VARCHAR}, #{item.name,jdbcType=VARCHAR},#{item.grade,jdbcType=VARCHAR},  #{item.phone,jdbcType=VARCHAR},#{item.sex,jdbcType=INTEGER})</foreach>
</insert>
<!--2.如果需要批量修改,参考如下(注意:数据库连接需要加上allowMultiQueries=true)-->
<update id="updList" parameterType="com.pojo.Student"><foreach collection="studentList" separator=";" item="item">update student<set><if test="item.name != null">name = #{item.name,jdbcType=VARCHAR},</if><if test="item.grade != null">grade = #{item.grade,jdbcType=VARCHAR},</if><if test="item.phone != null">phone = #{item.phone,jdbcType=VARCHAR},</if><if test="item.sex != null">sex = #{item.sex,jdbcType=INTEGER},</if></set>where id = #{item.id,jdbcType=VARCHAR}</foreach>
</update>
注意
需要批量修改时,数据库连接需要加上allowMultiQueries=true
参考网址
https://blog.csdn.net/u013322876/article/details/72859089

springboot 导入excel(数据批量导入)相关推荐

  1. java excel批量导入数据库数据_Java实现Excel数据批量导入数据库

    Java实现Excel数据批量导入数据库 概述: 这个小工具类是工作中的一个小插曲哦,因为提数的时候需要跨数据库导数... 有的是需要从oracle导入mysql ,有的是从mysql导入oracle ...

  2. arcgis导入excel数据_导入Excel数据到ArcGIS属性表的两种实用方法

    导入Excel数据到ArcGIS有两种方法,一种是用ArcMap的加载数据(黄色+号那个):另一种是用ArcCatalog直接转为shp文件,两种方法的原理是一样的. 第一种方法 1.Excel数据: ...

  3. Excel数据批量导入到数据库

    1.今天做批量导入网上找了个例子,改了改,运行起来了.用POI实现Excel的读取,需要jar包. 2.ReadExcel.java读取数据 /*** */ package com.b510.exce ...

  4. php批量导入多个excel,php的excel数据批量导入

    工作中常常有批量导入数据的需求,方法太多,掌握一个简单实用的足够了.下面为大家介绍一个好用的方法. 数据导入必须按照指定的格式系统方能识别,因此可两个大的步骤:一.导入模板下载  二.数据导入 一.模 ...

  5. matlab 批量导入excel,MATLAB  批量导入excel和txt文件的方法

    将一个文件目录下所有的文件名字全部倒入到一个文件中,除了使用ls函数以外,还可以使用 file=dir('C:\Users\Administrator\Desktop\MATLAB数据的导入导出以及试 ...

  6. php laravel导入excel,Laravel- 后台批量导入 Excel

    最近做的一个H5网站 有一个后台批量录入信息列表的功能,上网搜索了一下,发现了maatwebsite/excel 依赖,在此说明一下具体的实现流程. 1.安装 值得一提的是本人使用的是laravel ...

  7. python导入excel数据-Python导入数值型Excel数据并生成矩阵操作

    riginal_Data 因为程序是为了实现对纯数值型Excel文档进行导入并生成矩阵,因此有必要对第五列文本值进行删除处理. Import_Data import numpy as np impor ...

  8. 4 基于matplotlib的python数据可视化——导入Excel数据批量制作柱形图

    不同类型的图表有不同的功能.柱形图主要用于对比数据,折线图主要用于展示数据变化的趋势,散点图主要用于判断数据的相关性. 批量制作图表 员工销售业绩统计表:https://download.csdn.n ...

  9. php word 邮件合并发送邮件,WPS 邮件合并 30秒批量制作Word文档 Excel数据批量导入World指定位置...

    有时候因工作需要,会需要往Word文档里填入诸如姓名.性别.成绩之类的固定数据,但这些数据却在Excel表格里,且相同的Word内容需要输入这种数据成千上万.比如像学生录取通知书.准考证.奖状.座位图 ...

  10. python怎样导入excel数据_python导入excel数据

    1 .导入模块 import xlrd 2 .打开 Excel 文件读取数据 data = xlrd.open_workbook('excelFile.xls') 3 .使用技巧 获取一个工作表 ta ...

最新文章

  1. MySQL 5.7中的更多改进,包括计算列
  2. WCF方法拦截及OperationInvoker传递参数到WCF方法的实现
  3. oel6mysql_Linux7(CentOS,RHEL,OEL)和 Oracle RAC环境系列4:target(图形
  4. [原创] 为什么模除的时候一般建议选择素数来除?比如说hashtable的桶数会取一个素数...
  5. linux基础(一)
  6. maven工程导入eclipse后报错
  7. vue.js中mock本地json数据
  8. MySQL常见的两种存储引擎:MyISAM与InnoDB的爱恨情仇
  9. kvm上添加万兆网卡_烂泥:为KVM虚拟机添加网卡
  10. LINUX中使用fdisk对SD卡磁盘进行格式化并重新分区
  11. SpringBoot—整合log4j2入门和log4j2.xml配置详解
  12. STM32(一)----建立嵌入式STM32工程
  13. Python多线程(自学必备 超详细)
  14. [设计模式-行为型]模板方法模式(Template Method)
  15. 64位程序core分析
  16. 计算机黑屏的原因及解决办法,电脑突然黑屏重启的原因及解决办法
  17. Linux内核数据结构之 radix tree
  18. sram是靠什么存储信息
  19. 最新冰盾DDoS防火墙V9.1 新增防护功能更强大
  20. 1.3 anaconda的安装和使用

热门文章

  1. 游戏中的弹道学手册(转)
  2. (operational-transformations)ot算法两个字符串如何生成ot操作转换的工具
  3. 一元一次方程计算机在线,100道一元一次方程计算题41078.doc
  4. 为AI而生的IPU芯片,或挑战GPU的霸主位?
  5. 达摩院2021十大科技趋势:云原生重塑IT技术体系
  6. adb教程(很详细)
  7. 华为百度挺进“云手机”!5G时代的超级入口来了
  8. 京东案例开发之居家优品
  9. 亲自下场对抗名创优品,阿里的焦虑感在发作?
  10. STM8L在IAR编译时出现Warning[Pe188]: enumerated type mixed with another type F:\STM8Ldemo\Bsp\bsp警告处理