1.优化上传个人头像错误提示框。

2.增加bootstrap fileinput插件。
3.增加通过Excel文件批量添加用户功能。
This commit is contained in:
yangzhengze
2018-06-05 23:03:11 +08:00
parent c5b2b8d5ca
commit dcbd2b2210
24 changed files with 10614 additions and 85 deletions

View File

@ -0,0 +1,78 @@
package com.ruoyi.common.utils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import java.text.DecimalFormat;
import java.util.Date;
/**
* 导入Excel工具类
*/
public class ExcelImportUtils {
/** 是否是2003的excel返回true是2003Excel文件**/
public static boolean isExcel2003(String filePath){
return filePath.matches("^.+\\.(?i)(xls)$");
}
/** 是否是2007以上的excel返回true是2007Excel文件**/
public static boolean isExcel2007(String filePath){
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
/**
* 验证EXCEL文件
*
* @param filePath
* @return
*/
public static boolean validateExcel(String filePath) {
if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
return false;
}
return true;
}
/**
* 获取单元格的值
* @param cell
* @return
*/
public static String getCellValue(Cell cell) {
String value = "";
if (cell != null) {
switch(cell.getCellTypeEnum()){
case NUMERIC:// 数字
value = cell.getNumericCellValue()+ " ";
if(HSSFDateUtil.isCellDateFormatted(cell)){
Date date = cell.getDateCellValue();
if(date != null){
value = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,date); // 日期格式化
}else{
value = "";
}
}else {
// 解析cell时候 数字类型默认是double类型的 但是想要获取整数类型 需要格式化
value = new DecimalFormat("0").format(cell.getNumericCellValue());
}
break;
case STRING: // 字符串
value = cell.getStringCellValue();
break;
case BOOLEAN: // Boolean类型
value = cell.getBooleanCellValue()+"";
break;
case BLANK: // 空值
value = "";
break;
case ERROR: // 错误类型
value ="非法字符";
break;
default:
value = "未知类型";
break;
}
}
return value.trim();
}
}

View File

@ -1,18 +1,5 @@
package com.ruoyi.project.system.user.controller;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.web.controller.BaseController;
@ -25,6 +12,17 @@ import com.ruoyi.project.system.role.service.IRoleService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.domain.UserStatus;
import com.ruoyi.project.system.user.service.IUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
* 用户信息
@ -35,7 +33,7 @@ import com.ruoyi.project.system.user.service.IUserService;
@RequestMapping("/system/user")
public class UserController extends BaseController
{
private static final Logger log = LoggerFactory.getLogger(UserController.class);
private String prefix = "system/user";
@Autowired
@ -172,6 +170,28 @@ public class UserController extends BaseController
return userService.saveUser(user) > 0 ? Message.success() : Message.error();
}
/**
* 批量新增用户
*/
@RequiresPermissions("system:user:batchAdd")
@Log(title = "系统管理", action = "用户管理-批量新增用户")
@PostMapping("/batchAdd")
@Transactional(rollbackFor = Exception.class)
@ResponseBody
public Message batchAdd( @RequestParam("uploadfile") MultipartFile file)
{
try {
if(!file.isEmpty()){
int rows=userService.batchImportUsers(file);
return Message.success(String.valueOf(rows));
}
return Message.error();
}catch (Exception e){
log.error("批量添加用户失败 !", e);
return Message.error(e.getMessage());
}
}
/**
* 校验用户名
*/

View File

@ -1,8 +1,9 @@
package com.ruoyi.project.system.user.mapper;
import java.util.List;
import com.ruoyi.project.system.user.domain.User;
import java.util.List;
/**
* 用户表 数据层
*
@ -108,4 +109,12 @@ public interface UserMapper
* @return 结果
*/
public User checkEmailUnique(String email);
/**
* 批量添加用户
* @param userList
* @return
*/
public int batchAddUser(List<User> userList);
}

View File

@ -1,7 +1,9 @@
package com.ruoyi.project.system.user.service;
import java.util.List;
import com.ruoyi.project.system.user.domain.User;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
* 用户 业务层
@ -133,4 +135,11 @@ public interface IUserService
*/
public String selectUserPostGroup(Long userId);
/**
* Excel批量导入用户
* @param myFile
* @return
*/
public int batchImportUsers(MultipartFile myFile);
}

View File

@ -1,13 +1,13 @@
package com.ruoyi.project.system.user.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.common.utils.ExcelImportUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.shiro.service.PasswordService;
import com.ruoyi.project.system.dept.domain.Dept;
import com.ruoyi.project.system.dept.service.IDeptService;
import com.ruoyi.project.system.post.domain.Post;
import com.ruoyi.project.system.post.mapper.PostMapper;
import com.ruoyi.project.system.role.domain.Role;
@ -18,6 +18,19 @@ import com.ruoyi.project.system.user.domain.UserRole;
import com.ruoyi.project.system.user.mapper.UserMapper;
import com.ruoyi.project.system.user.mapper.UserPostMapper;
import com.ruoyi.project.system.user.mapper.UserRoleMapper;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.*;
/**
* 用户 业务层处理
@ -27,7 +40,7 @@ import com.ruoyi.project.system.user.mapper.UserRoleMapper;
@Service("userService")
public class UserServiceImpl implements IUserService
{
private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
@Autowired
private UserMapper userMapper;
@ -46,6 +59,10 @@ public class UserServiceImpl implements IUserService
@Autowired
private PasswordService passwordService;
@Autowired
private IDeptService deptService;
/**
* 根据条件分页查询用户对象
*
@ -178,6 +195,245 @@ public class UserServiceImpl implements IUserService
return count;
}
/**
* 根据Execl 批量保存用户
* 1. 使用HSSFWorkbook 打开或者创建 “Excel对象”
* 2. 用HSSFWorkbook返回对象或者创建sheet对象
* 3. 用sheet返回行对象用行对象得到Cell对象
* 4. 对Cell对象进行读写
* @param myFile
* @return
*/
@Override
public int batchImportUsers(MultipartFile myFile) {
//Excel工作簿
Workbook workbook=null;
//获取文件名
String filename=myFile.getOriginalFilename();
log.info("【ExeclfileName】{}",filename);
//根据文件名判断文件是2003版本还是2007版本
if(ExcelImportUtils.isExcel2003(filename)){
try {
workbook=new HSSFWorkbook(myFile.getInputStream());//2003版本
}catch (IOException e){
log.error("获取Excel2003流错误"+e.getMessage());
}
}else if(ExcelImportUtils.isExcel2007(filename)){
try {
workbook=new XSSFWorkbook(myFile.getInputStream());//2007以上版本
}catch (IOException e){
log.error("获取Excel2007以上版本流错误"+e.getMessage());
}
}else{
throw new UserException("1000",new Object[]{"文件不是Excel格式"});
}
//得到第一个sheet
Sheet sheet = workbook.getSheetAt(0);
//得到Excel的行数
int totalRows = sheet.getLastRowNum();
log.info("【rows】{}",totalRows);
//新建用户list
List<User> users=new ArrayList<User>();
List<Dept> depts;
List<Role> roles;
List<Post> posts;
//如果行数为空
/**
* getPhysicalNumberOfRows
*
* 获取有记录的行数最后有数据的行是第n行前面有m行是空行没数据则返回n-m
*/
if((totalRows==0)&&(sheet.getPhysicalNumberOfRows()==0)){
throw new UserException("1001",new Object[]{"数据为空 请填写数据"});
}else{
//获取全部部门信息
depts=deptService.selectDeptAll();
//获取全部角色信息
roles=roleMapper.selectRolesAll();
//获取全部岗位信息
posts=postMapper.selectPostAll();
}
for(int i=1;i<=totalRows;i++){
Row row = sheet.getRow(i);
if(row!=null){
User user=new User();
//登录名(用户名)
String userName=ExcelImportUtils.getCellValue(row.getCell(0));
if(userName.isEmpty()){
continue;
}else{
//判断用户名是否唯一
if(checkLoginNameUnique(userName).equals(UserConstants.USER_NAME_UNIQUE)){
user.setLoginName(userName);
}else {
log.error("【rows】{}行用户名已经存在",i+1);
continue;
}
}
//姓名
String userRealName=ExcelImportUtils.getCellValue(row.getCell(1));
user.setUserName(userRealName);
//性别
String userSex=ExcelImportUtils.getCellValue(row.getCell(2));
if(StringUtils.isNotEmpty(userSex)){
if(userSex.equals("")){
user.setSex("0");
}else if(userSex.equals("")){
user.setSex("1");
}else {
user.setSex("2");
}
}
//密码
String passWord=ExcelImportUtils.getCellValue(row.getCell(3));
user.randomSalt();
user.setPassword(passwordService.encryptPassword(userName, passWord, user.getSalt()));
//部门
String dept=ExcelImportUtils.getCellValue(row.getCell(4));
if(StringUtils.isNotEmpty(dept)){
for (int k=0;k<depts.size();k++){
if(dept.equals(depts.get(k).getDeptName())){
user.setDeptId(depts.get(k).getDeptId());
break;
}
}
}
user.setCreateBy(ShiroUtils.getLoginName());
//角色--多个角色以","分割
String userRolesExcel=ExcelImportUtils.getCellValue(row.getCell(5));
if(StringUtils.isNotEmpty(userRolesExcel)){
//Set可以去掉重复的值
Set<Long> sets=new HashSet<Long>();
//判断是否有"," 号
if(userRolesExcel.contains(",")){
List<String> results= Arrays.asList(userRolesExcel.split(","));
for(String s:results){
for(int l=0;l<roles.size();l++){
if(s.equals(roles.get(l).getRoleName())){
sets.add(roles.get(l).getRoleId());
break;
}
}
}
}else {
for(int j=0;j<roles.size();j++){
if(userRolesExcel.equals(roles.get(j).getRoleName())){
sets.add(roles.get(j).getRoleId());
break;
}
}
}
for(Long longTes:sets){
log.info("username={},longTes={}",userName,longTes);
}
user.setRoleIds((Long[]) sets.toArray(new Long[sets.size()]));
}
//岗位--多个岗位以","分割
String userPostExcel=ExcelImportUtils.getCellValue(row.getCell(6));
if(StringUtils.isNotEmpty(userPostExcel)){
//去掉重复的值,
Set<Long> setPosts=new HashSet<Long>();
//判断是否有"," 号
if(userPostExcel.contains(",")){
List<String> resultsp= Arrays.asList(userPostExcel.split(","));
for(String p:resultsp){
for(int h=0;h<posts.size();h++){
if(p.equals(posts.get(h).getPostName())){
setPosts.add(posts.get(h).getPostId());
break;
}
}
}
}else {
for(int m=0;m<posts.size();m++){
if(userPostExcel.equals(posts.get(m).getPostName())){
setPosts.add(posts.get(m).getPostId());
break;
}
}
}
for(Long longTest:setPosts){
log.info("username={},longTest={}",userName,longTest);
}
user.setPostIds((Long[]) setPosts.toArray(new Long[setPosts.size()]));
}
//手机号
String phoneNumber=ExcelImportUtils.getCellValue(row.getCell(7));
if(StringUtils.isNotEmpty(phoneNumber)){
//验证是否是手机号
if(phoneNumber.matches(UserConstants.MOBILE_PHONE_NUMBER_PATTERN)){
user.setPhonenumber(phoneNumber);
}
}
//邮箱
String userEmail=ExcelImportUtils.getCellValue(row.getCell(8));
if(StringUtils.isNotEmpty(userEmail)){
//验证是否是邮箱
if(userEmail.matches(UserConstants.EMAIL_PATTERN)){
user.setEmail(userEmail);
}
}
users.add(user);
}
}
//实际添加行数
int realRow=0;
//如果添加的列表不为空
if(users.size()>0){
//批量插入用户
realRow=userMapper.batchAddUser(users);
}
System.out.println(realRow);
if(realRow>0){
//用户和角色关联
List<UserRole> userRoles=new ArrayList<UserRole>();
//用户和岗位关联
List<UserPost> userPosts=new ArrayList<UserPost>();
for(User test:users){
System.out.println("userID="+test.getUserId());
System.out.println("username="+test.getUserName());
System.out.println("useroleids"+Arrays.toString(test.getRoleIds()));
System.out.println("userpostids"+Arrays.toString(test.getPostIds()));
//添加用户-角色关联表
for(int q=0;q<test.getRoleIds().length;q++){
UserRole userRole=new UserRole();
userRole.setUserId(test.getUserId());
userRole.setRoleId(test.getRoleIds()[q]);
userRoles.add(userRole);
}
for(int r=0;r<test.getPostIds().length;r++){
UserPost userPost=new UserPost();
userPost.setUserId(test.getUserId());
userPost.setPostId(test.getPostIds()[r]);
userPosts.add(userPost);
}
}
//批量添加用户-角色关联数据
userRoleMapper.batchUserRole(userRoles);
//批量添加用户-岗位关联数据
userPostMapper.batchUserPost(userPosts);
;
}
return realRow;
}
/**
* 修改用户信息
*