两种方式导入excel

article/2025/9/9 7:21:48

第一种 easyExcel

pom文件导入

com.alibaba
easyexcel
2.2.3

然后
/**
* 导入用户excel
* @param
* @return
*/
@PostMapping(“manage/imporAcc”)
Message<?> imporAcc(@RequestParam(“accountFile”) MultipartFile file,@RequestParam(“role”)String role,@RequestParam(“password”)String password) throws IOException {

    log.info("导入用户数据文件,角色为:{},密码为:{}",role,password);if(file.isEmpty()){return R.error(Msg.ERROR_CHECK_EMPTY,"导入数据文件");}return userAccService.imporAcc(file,role,password);
}

在这里插入图片描述

controller层

然后
service层

/**
* 导入账户数据文件
* @param file
* @return
*/
public Message<?> imporAcc(MultipartFile file,String role,String password) {

    InputStream inputStream = null;Integer errNum=0;try {inputStream = file.getInputStream();} catch (IOException e) {e.printStackTrace();}EasyExcel.read(inputStream, UserAccountImportEntity.class, new AnalysisEventListener<UserAccountImportEntity>() {@Overridepublic void invoke(UserAccountImportEntity data, AnalysisContext context) {System.out.println("--------------------------");System.out.println(data);String dataContextt = data.getDataRange();if("全部数据".equals(dataContextt)){dataContextt="all";}else if("泛渠道".equals(dataContextt)){dataContextt="tx_channel";}else{}AccountEntity account = userAccService.findAccountByNum(data.getAccountNum());//校验归属渠道是否和渠道ID匹配String hallNo = data.getHallNo();//渠道名称String channleId = data.getChannleId();//渠道IdTbPlatformChannelVo tbPlatformChannelVo = channelFeign.findByHallNo(channleId).getBody();String branchName = tbPlatformChannelVo.getBranchName();if(hallNo.equals(branchName)){if (account == null) {account = new AccountEntity();BeanUtils.copyProperties(data, account);account.setState(StatusCons.E);account.setPassword(password);//如果不绑定用户 则新建用户if (account.getUserId() == null) {UserEntity user = new UserEntity();user.setState(StatusCons.E);user.setUserName(data.getUserName());user.setDataContext(dataContextt);userAccService.addUser(user);account.setUserId(user.getUserId());}//如果角色不为空 设置角色ArrayList<Long> list=new ArrayList<Long>();list.add(Long.parseLong(role));Long[] newRoles = new Long[list.size()];Long[] roles = list.toArray(newRoles);if (roles != null) {userAccService.setRole(account.getUserId(), roles);}account.setPassword(passwordEncoder.encode(account.getPassword()));account.setHallNo(channleId);Message<?> message = userAccService.addAccount(account);//根据地市的名称和区县的名称查询对应的编码String cityName = data.getCityName();String areaName = data.getAreaName();String cityCode="";String areaCode="";List<String> stringList = trAccountAreaService.queryCodeByCityName(cityName);if(!CollectionUtils.isEmpty(stringList)){cityCode=stringList.get(0);}List<String> stringList1 = trAccountAreaService.queryCodeByCityName(areaName);if(!CollectionUtils.isEmpty(stringList1)){areaCode=stringList.get(0);}ArrayList<Long> areas=new ArrayList<Long>();areas.add(Long.parseLong(cityCode));areas.add(Long.parseLong(areaCode));Long[] areaList = new Long[areas.size()];for(int i = 0; i < areas.size();i++){areaList[i] = areas.get(i);}// Long[] areanews = list.toArray(areaList);//账户区域关联表新增if(areaList.length>0){userAccController.saveAreaByAccount(Long.parseLong(String.valueOf(message.getBody())),areaList);}}else{}}else{}}@Overridepublic void doAfterAllAnalysed(AnalysisContext context) {System.out.println("导入账户数据文件完成");}}).sheet().doRead();return R.success(errNum);
}

在这里插入图片描述

在这里插入图片描述

需要注意的是实体类

public class UserAccountImportEntity {

@ApiModelProperty("账号")
@ExcelProperty("账号")
@ColumnWidth(15)
private String accountNum;
@ExcelProperty("手机号码")
@ColumnWidth(15)
private String phone;
@ApiModelProperty("用户名称")
@ExcelProperty("用户名称")
@ColumnWidth(15)
private String userName;
@ApiModelProperty("Boss工号")
@ExcelProperty("Boss工号")
@ColumnWidth(15)
private String bossJobNum;
@ApiModelProperty("归属地市")
@ExcelProperty("归属地市")
@ColumnWidth(15)
private String cityName;
@ApiModelProperty("归属区县")
@ExcelProperty("归属区县")
@ColumnWidth(15)
private String  areaName;
@ExcelProperty("归属网格")
@ApiModelProperty("归属网格")
@ColumnWidth(15)
private String excludeNet;
@ExcelProperty("商家/连锁店")
@ApiModelProperty("商家/连锁店")
@ColumnWidth(25)
private String shopKeeper;
@ApiModelProperty("归属渠道")
@ExcelProperty("归属渠道")
@ColumnWidth(15)
private String hallNo;
@ApiModelProperty("渠道ID")
@ExcelProperty("渠道ID")
private String channleId;
@ExcelProperty("数据范围")
@ApiModelProperty("数据范围")
@ColumnWidth(15)
private String dataRange;
@ApiModelProperty("密码")
@ExcelIgnore
private String password;
@ApiModelProperty("角色")
@ExcelIgnore
private String roleId;public UserAccountImportEntity(){}public UserAccountImportEntity(String accountNum, String userName, String bossJobNum, String cityName, String areaName, String excludeNet, String shopKeeper, String hallNo, String channleId, String dataRange, String password, String roleId,String phone) {this.accountNum = accountNum;this.phone = phone;this.userName = userName;this.bossJobNum = bossJobNum;this.cityName = cityName;this.areaName = areaName;this.excludeNet = excludeNet;this.shopKeeper = shopKeeper;this.hallNo = hallNo;this.channleId = channleId;this.dataRange = dataRange;this.password = password;this.roleId = roleId;
}public String getAccountNum() {return accountNum;
}public void setAccountNum(String accountNum) {this.accountNum = accountNum;
}public String getPhone() {return phone;
}public void setPhone(String phone) {this.phone = phone;
}public String getUserName() {return userName;
}public void setUserName(String userName) {this.userName = userName;
}public String getBossJobNum() {return bossJobNum;
}public void setBossJobNum(String bossJobNum) {this.bossJobNum = bossJobNum;
}public String getCityName() {return cityName;
}public void setCityName(String cityName) {this.cityName = cityName;
}public String getAreaName() {return areaName;
}public void setAreaName(String areaName) {this.areaName = areaName;
}public String getExcludeNet() {return excludeNet;
}public void setExcludeNet(String excludeNet) {this.excludeNet = excludeNet;
}public String getShopKeeper() {return shopKeeper;
}public void setShopKeeper(String shopKeeper) {this.shopKeeper = shopKeeper;
}public String getHallNo() {return hallNo;
}public void setHallNo(String hallNo) {this.hallNo = hallNo;
}public String getChannleId() {return channleId;
}public void setChannleId(String channleId) {this.channleId = channleId;
}public String getDataRange() {return dataRange;
}public void setDataRange(String dataRange) {this.dataRange = dataRange;
}public String getPassword() {return password;
}public void setPassword(String password) {this.password = password;
}public String getRoleId() {return roleId;
}public void setRoleId(String roleId) {this.roleId = roleId;
}@Override
public String toString() {return "UserAccountImportEntity{" +"accountNum='" + accountNum + '\'' +", phone='" + phone + '\'' +", userName='" + userName + '\'' +", bossJobNum='" + bossJobNum + '\'' +", cityName='" + cityName + '\'' +", areaName='" + areaName + '\'' +", excludeNet='" + excludeNet + '\'' +", shopKeeper='" + shopKeeper + '\'' +", hallNo='" + hallNo + '\'' +", channleId='" + channleId + '\'' +", dataRange='" + dataRange + '\'' +", password='" + password + '\'' +", roleId='" + roleId + '\'' +'}';
}

}

下面是用POI原始方法做excel

controller层

/**
* 备用接口 用POI导出用户excel
* @param
* @return
*/
@PostMapping(“manage/imporPoiAcc”)
Message<?> imporPoiAcc(@RequestParam(“accountFile”) MultipartFile file,@RequestParam(“role”)String role,@RequestParam(“password”)String password) throws IOException {

    log.info("导入用户数据文件,角色为:{},密码为:{}",role,password);if (!FileUtil.checkExtension(file)){return R.error(Msg.ERROR_CHECK_EMPTY,"导入数据文件");}if(!FileUtil.isOfficeFile(file)){return R.error(Msg.ERROR_CHECK_EMPTY,"导入数据文件");}if(StringUtils.isBlank(role)){return R.error(Msg.ERROR_CHECK_EMPTY,"输入角色");}if(StringUtils.isBlank(password)){return R.error(Msg.ERROR_CHECK_EMPTY,"输入密码");}return userAccService.imporPoiAcc(file,role,password);
}

下面是工具类
FileUtil

public class FileUtil {

public static Boolean isOfficeFile(InputStream inputStream){boolean result = false;try {FileMagic fileMagic = FileMagic.valueOf(inputStream);if (Objects.equals(fileMagic,FileMagic.OLE2)||Objects.equals(fileMagic,fileMagic.OOXML)){result = true;}} catch (IOException e) {e.printStackTrace();}return result;
}/*** 判断是否office文件* @param file* @return* @throws IOException*/
public static Boolean isOfficeFile(MultipartFile file) throws IOException {BufferedInputStream bufferedInputStream = new BufferedInputStream(file.getInputStream());boolean result = false;result = isOfficeFile(bufferedInputStream);return result;
}/*** 判断扩展名是否是excel扩展名* @param extension* @return*/
public static Boolean checkExtension(String extension){return Lists.newArrayList("xls","xlsx","XLS","XLSX").contains(extension);
}/*** 判断扩展名是否是excel扩展名* @param file* @return*/
public static Boolean checkExtension(MultipartFile file){String fileName = file.getOriginalFilename();String extension = fileName.substring(fileName.lastIndexOf(".")+1);return checkExtension(extension);
}/*** 自动判断文件类型* @param file* @return* @throws IOException*/
public static Workbook getWorkbookAuto(MultipartFile file) throws IOException {/** 判断文件的类型,是2003还是2007 */boolean isExcel2003 = true;if (isExcel2007(file.getOriginalFilename())) {isExcel2003 = false;}BufferedInputStream is = new BufferedInputStream(file.getInputStream());Workbook wb;if (isExcel2003) {wb = new HSSFWorkbook(is);} else {wb = new XSSFWorkbook(is);}return wb;
}public static boolean isExcel2003(String filePath) {return filePath.matches("^.+\\.(?i)(xls)$");
}public static boolean isExcel2007(String filePath) {return filePath.matches("^.+\\.(?i)(xlsx)$");
}

}

然后是service层
public Message<?> imporPoiAcc(MultipartFile file, String role, String password) {

    //未进入数据库行数Integer errNum=0;try {//正确的文件类型 自动判断2003或者2007Workbook workbook = FileUtil.getWorkbookAuto(file);Sheet sheet = workbook.getSheetAt(0);//默认只有一个sheet//判断这个sheet的列数Row row0 = sheet.getRow(0);short lastCellNum = row0.getLastCellNum();if(lastCellNum<11){return R.error("sheet列数不正确");}int rows = sheet.getPhysicalNumberOfRows();//获得sheet有多少行//读第一个sheetfor (int i = 1;i<rows;i++){Row row = sheet.getRow(i);Cell cell0 = row.getCell(0);String accountNum="";if(cell0!=null){cell0.setCellType(CellType.STRING);accountNum = cell0.getStringCellValue();}Cell cell1 = row.getCell(1);String phone="";if(cell1!=null){cell1.setCellType(CellType.STRING);phone = cell1.getStringCellValue();}Cell cell2 = row.getCell(2);String userName="";if(cell2!=null){cell2.setCellType(CellType.STRING);userName = cell2.getStringCellValue();}Cell cell3 = row.getCell(3);String bossJobNum="";if(cell3!=null){cell3.setCellType(CellType.STRING);bossJobNum = cell3.getStringCellValue();}Cell cell4 = row.getCell(4);String cityName="";if(cell4!=null){cell4.setCellType(CellType.STRING);cityName = cell4.getStringCellValue();}Cell cell5 = row.getCell(5);String areaName ="";if(cell5!=null){cell5.setCellType(CellType.STRING);areaName = cell5.getStringCellValue();}Cell cell6 = row.getCell(6);String excludeNet="";if(cell6!=null){cell6.setCellType(CellType.STRING);excludeNet = cell6.getStringCellValue();}Cell cell7 = row.getCell(7);String shopKeeper="";if(cell7!=null){cell7.setCellType(CellType.STRING);shopKeeper = cell7.getStringCellValue();}Cell cell8 = row.getCell(8);String hallNo="";if(cell8!=null){cell8.setCellType(CellType.STRING);hallNo = cell8.getStringCellValue();}Cell cell9 = row.getCell(9);String channleId="";if(cell9!=null){cell9.setCellType(CellType.STRING);channleId = cell9.getStringCellValue();//根据渠道ID查询渠道名称TbPlatformChannelVo tbPlatformChannelVo = channelFeign.findByHallNo(channleId).getBody();if(tbPlatformChannelVo==null){errNum++;continue;}else{if(!tbPlatformChannelVo.getBranchName().equals(hallNo)){errNum++;continue;}}}Cell cell10 = row.getCell(10);String dataRange="";if(cell10!=null){cell10.setCellType(CellType.STRING);dataRange = cell10.getStringCellValue();if("全部数据".equals(dataRange)){dataRange="all";}else if("泛渠道".equals(dataRange)){dataRange="tx_channel";}else{errNum++;continue;}}//根据地市的名称和区县的名称查询对应的编码String cityCode="";String areaCode="";List<String> stringList = trAccountAreaService.queryCodeByCityName(cityName);if(!CollectionUtils.isEmpty(stringList)){cityCode=stringList.get(0);}else{errNum++;continue;}List<String> stringList1 = trAccountAreaService.queryCodeByCityName(areaName);if(!CollectionUtils.isEmpty(stringList1)){areaCode=stringList1.get(0);}else{errNum++;continue;}//判断是否有此账号之前AccountEntity accountEntity = userAccService.findAccountByNum(accountNum);Long userId=0L;Message<?> accMessage=null;if(accountEntity==null){//数据库导入userUserEntity user = new UserEntity();user.setState(StatusCons.E);user.setUserName(userName);user.setDataContext(dataRange);userAccService.addUser(user);//数据库新增账号userId=user.getUserId();accountEntity=new AccountEntity();accountEntity.setState(StatusCons.E);accountEntity.setAccountNum(accountNum);accountEntity.setUserId(userId);accountEntity.setPassword(passwordEncoder.encode(password));accountEntity.setHallNo(channleId);accountEntity.setBossJobNum(bossJobNum);accountEntity.setPhone(phone);accMessage = userAccService.addAccount(accountEntity);}else{errNum++;continue;}//如果角色不为空 设置角色ArrayList<Long> list=new ArrayList<Long>();list.add(Long.parseLong(role));Long[] newRoles = new Long[list.size()];Long[] roles = list.toArray(newRoles);if (roles != null) {userAccService.setRole(userId, roles);}ArrayList<Long> areas=new ArrayList<Long>();areas.add(Long.parseLong(cityCode));areas.add(Long.parseLong(areaCode));Long[] areaList = new Long[areas.size()];for(int k = 0; k < areas.size();k++){areaList[k] = areas.get(k);}//账户区域关联表新增if(areaList.length>0){userAccController.saveAreaByAccount(Long.parseLong(String.valueOf(accMessage.getBody())),areaList);}}} catch (IOException e) {e.printStackTrace();}if(errNum>0){return R.error(Msg.ERROR_BUSS_SMS_CM_IMPORT,errNum+"行");}else{return R.success();}
}

在这里插入图片描述


http://chatgpt.dhexx.cn/article/0mBeYS4L.shtml

相关文章

Java实现Excel导入和导出,看这一篇就够了(珍藏版)

目录 目录 前言 1. 功能测试 1.1 测试准备 1.2 数据导入 1.2.1 导入解析为JSON 1.2.2 导入解析为对象&#xff08;基础&#xff09; 1.2.3 导入解析为对象&#xff08;字段自动映射&#xff09; 1.2.4 导入解析为对象&#xff08;获取行号&#xff09; 1.2.5 导入解析…

常见机器学习面试题

参考&#xff1a;http://kubicode.me/2015/08/16/Machine%20Learning/Common-Interview/?fromsinglemessage# http://blog.csdn.NET/heyongluoyao8/article/details/49429629 http://lib.csdn.Net/article/machinelearning/33798 http://www.cnblogs.com/zuochongyan/p/540705…

机器学习面试题60~100

61.说说梯度下降法 LeftNotEasy&#xff0c;本题解析来源&#xff1a;http://www.cnblogs.com/LeftNotEasy/archive/2010/12/05/mathmatic_in_machine_learning_1_regression_and_gradient_descent.html 下面是一个典型的机器学习的过程&#xff0c;首先给出一个输入数据&#…

深度学习机器学习面试题汇——模型优化,轻量化,模型压缩

深度学习机器学习面试题汇——模型优化&#xff0c;轻量化&#xff0c;模型压缩 提示&#xff1a;互联网大厂可能考的面试题 若CNN网络很庞大&#xff0c;在手机上运行效率不高&#xff0c;对应模型压缩方法有了解吗 介绍一下模型压缩常用的方法&#xff1f;为什么用知识蒸馏&…

Python干货:破解40大机器学习面试题(包含初中高级)

机器学习&#xff08;ML&#xff09;是我们世界的未来。在未来的几年中&#xff0c;几乎每种产品都将包含ML组件。ML预计将从2020年的$ 7.3B增长到2024年的$ 30.6B。对ML技能的需求遍及整个行业。 机器学习面试是一个严格的过程&#xff0c;在此过程中&#xff0c;应聘者会评估…

2021机器学习面试必考面试题汇总(附答案详解)

问题&#xff1a;Xgboost、lightGBM和Catboost之间的异同&#xff1f; 树的特征 三种算法基学习器都是决策树&#xff0c;但是树的特征以及生成的过程仍然有很多不同。 CatBoost使用对称树&#xff0c;其节点可以是镜像的。CatBoost基于的树模型其实都是完全二叉树。 XGBoo…

机器学习面试题之——简单介绍最小二乘

1、常用到的最小二乘场合&#xff1a;最小二乘法直线拟合&#xff0c;最小二乘法多项式&#xff08;曲线&#xff09;拟合&#xff0c;机器学习中线性回归的最小二乘法&#xff0c;系统辨识中的最小二乘辨识法&#xff0c;参数估计中的最小二乘法&#xff0c;等等。 2、为什么…

AI人工智能、机器学习 面试题(2022最新版)

人工智能、机器学习面试题总结&#xff0c;侧重于理解&#xff0c;回答供参考&#xff0c;欢迎讨论。 General 深度学习&#xff08;Deep Learning, DL&#xff09;和机器学习&#xff08;Machine Learning, ML&#xff09;的关系是什么&#xff1f; 深度学习是机器学习的子类…

面试官最爱用的统计学、数据科学、机器学习面试题答案

【导读】本文盘点了数据科学和机器学习面试中的常见问题&#xff0c;着眼于不同类型的面试问题。如果您计划向数据科学领域转行&#xff0c;这些问题一定会有所帮助。 技术的不断进步使得数据和信息的产生速度今非昔比&#xff0c;并且呈现出继续增长的趋势。此外&#xff0c;…

41个机器学习面试题

####41 Essential Machine Learning Interview Questions (with answers) <font color‘orange’&#xff0c;size5>一、算法理论 Q1: 什么是偏倚&#xff08;bias&#xff09;、方差&#xff08;variable&#xff09;均衡&#xff1f; 偏倚指的是模型预测值与真实值的…

推荐收藏,25道机器学习面试问题(附答案)

近年来&#xff0c;对深度学习的需求不断增长&#xff0c;其应用程序被应用于各个商业部门。各公司现在都在寻找能够利用深度学习和机器学习技术的专业人士。 在本文中&#xff0c;将整理深度学习面试中最常被问到的25个问题和答案。如果你最近正在参加深度学习相关的面试工作…

机器学习面试题之机器学习基础(一)

1、L1与L2正则化 他们都是可以防止过拟合&#xff0c;降低模型复杂度。 L1会趋向于产生少量的特征&#xff0c;而其他的特征都是0&#xff1b;L2会选择更多的特征&#xff0c;这些特征都会接近于0。L1在特征选择时非常有用&#xff0c;L2就只是一种规则化而已。 简单总结一下就…

机器学习面试必考面试题汇总—附解析

问题&#xff1a;xgboost对特征缺失敏感吗&#xff0c;对缺失值做了什么操作&#xff0c;存在什么问题 不敏感&#xff0c;可以自动处理&#xff0c;处理方式是将missing值分别加入左节点 右节点取分裂增益最大的节点将missing样本分裂进这个节点 。这种处理方式的问题在xgboo…

机器学习面试题——聚类算法

机器学习面试题——聚类算法 提示&#xff1a;互联网大厂经常考的传统机器学习算法 文章目录 机器学习面试题——聚类算法[TOC](文章目录) 题目k-means介绍一下&#xff0c;K-means的过程k-means优缺点k-means的簇&#xff08;k簇&#xff09;怎么选&#xff0c;K-means如何选取…

机器学习面试题目整理

0 调参技巧 清洗数据&#xff0c;数据预处理&#xff0c;数据增广是否使用预训练模型使用BN在过拟合后&#xff0c;使用正则化技巧如L1、L2、Dropout对于不均匀样本&#xff0c;使用重采样使用合适的优化器。第一&#xff0c;如果你关心快速收敛&#xff0c;使用自适应优化器&…

面试 | 22道机器学习常见面试题目

(1) 无监督和有监督算法的区别&#xff1f; 有监督学习&#xff1a;对具有概念标记&#xff08;分类&#xff09;的训练样本进行学习&#xff0c;以尽可能对训练样本集外的数据进行标记&#xff08;分类&#xff09;预测。这里&#xff0c;所有的标记&#xff08;分类&#xf…

最基本的25道深度学习面试问题和答案

近年来&#xff0c;对深度学习的需求不断增长&#xff0c;其应用程序被应用于各个商业部门。各公司现在都在寻找能够利用深度学习和机器学习技术的专业人士。在本文中&#xff0c;将整理深度学习面试中最常被问到的25个问题和答案。如果你最近正在参加深度学习相关的面试工作&a…

机器学习高频面试题(41道)

Q1: What’s the trade-off between bias and variance? 问题1: 什么是偏差&#xff08;bias&#xff09;、方差&#xff08;variable&#xff09;之间的均衡&#xff1f; Bias 是由于你使用的学习算法过度简单地拟合结果或者错误地拟合结果导致的错误。它反映的是模型在样本…

总结了200道经典的机器学习面试题(附参考答案)

刷题&#xff0c;是面试前的必备环节。本文总结了往年BAT机器学习面试题&#xff0c;干货满满&#xff0c;值得收藏。 想要入职大厂可谓是千军万马过独木桥。 为了通过层层考验&#xff0c;刷题肯定是必不可少的。本文根据网络在线发布的BAT机器学习面试1000题系列&#xff0…

微信小程序—域名配置(图文)

微信小程序—域名配置 1、微信公众平台登录 进入后选择‘开发’ 选择‘开发设置’ 域名配置&#xff0c;输入easy-mock即可&#xff08;因为我用的地址就是easy-mock&#xff0c;如果用的是豆瓣接口就直接域名配置成豆瓣的就行&#xff09; 2、打开右上角的详情 选择不校验…