xls格式的文件导入

<p>
<span style="color:#ff0000;">首先建立  一个名为importUser.js文件,文件内容</span></p>
var freshPage = false;
/**
 * 导入
 */
function uploadUser() {
	var html = createImportUserHtml();
	art.dialog.through({
				id : 'importUsers',
				title : '用户导入',
				content : html,
				lock : true,
				button : [{
							name : '验 证',
							callback : function() {
								checkFileFormat();
								return false;
							}
			-7			}, {
							name : '导 入',
							callback : function() {
								startAjaxFileUpload();
								return false;
							}
						}, {
							name : '取 消',
							callback : function() {
								return true;
							}
						}]
			});

}

/**
 * 验证格式
 */
function checkFileFormat() {

	var fileName = $("#fileToUpload").val();
	if (fileName == "") {
		$("#msg").html('请选择要验证的文件!');
		return false;
	}else{
		if(fileName.indexOf(".xls")==-1){
			$("#msg").html('请选择电子表格!');
			return false;
		}
	}
	var radioType = 1;
	var url = basePath + 'userUpload/check.action';
	$("#msg").html('');
	$.ajaxFileUpload({
				url : url,
				secureuri : false,
				fileElementId : 'fileToUpload',
				dataType : 'text',
				data : {
					uploadFileName : fileName,
					radioType : radioType
				},
				success : function(data, status) {
					if (data == "") {
						$("#msg").html("验证通过,可以导入!");

					} else {
						$("#msg").html(data);
					}
				},
				error : function(data, status, e) {

					$("#msg").html("对不起!验证文件时出错!");
				}
			})
	return false;

}

/**
 * 开始上传
 * 
 * @return {Boolean}
 */
function startAjaxFileUpload() {
	var fileName = $("#fileToUpload").val();
	if (fileName == "") {
		$("#msg").html('请选择要验证的文件!');
		return false;
	}else{
		if(fileName.indexOf(".xls")==-1){
			$("#msg").html('请选择电子表格!');
			return false;
		}
	}
	var radioType = $("input:radio[name='radioType']:checked").val();
	var url = basePath + 'userUpload/importUser.action';
	$("#msg").html('正在导入,请稍候......');
	$.ajaxFileUpload({
				url : url,
				secureuri : false,
				fileElementId : 'fileToUpload',
				dataType : 'text',
				data : {
					uploadFileName : fileName,
					radioType : radioType
				},
				success : function(data, status) {
					$("#msg").html(data);
					if(null != data && data.indexOf("共") == 0 ){
						freshPage = true;
						$("#page").attr("src",
								basePath + 'logined/user/userList.jsp');
						refreshTree("gid_0");
					}					
				},
				error : function(data, status, e) {
					$("#msg").html("对不起!导入文件时出错!");
				}
			})

	return false;

}

function createImportUserHtml() {
	var html = '<div><table width="400px" border="0" style="font-size:  12px; table-layout:auto;">';
	html += '<tr>';
	html += '  <th  style="width:100px;text-align:right;padding-right:5px">选择导入文件:</th>';
	html += '  <td><input type="file" name="fileToUpload" id="fileToUpload" style="width:260px; height:23px; line-height:23px;"/></td>';
	html += '</tr>';
	html += '<tr>';
	html += '	<th></th>';
	html += '	<td style="color:#999999;height:50px;">只支持<b> .xls </b>格式文件    ';
	html += '      <font><a style="color:#f00;TEXT-DECORATION:none" id="importModule" href="'
			+ basePath + 'down/userlist.xls' + '">获取模板?</a></font>';
	html += '   </td></tr>';
	html += '<tr><td colspan="2" align="center"><p id="msg" style="color: red;height:20px"></p></td></tr>';
	html += '</table></div>';
	return html;
}

 其中 里面跳转配置文件内容为**.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
        "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>

    <package name="userUpload" extends="struts-default" namespace="/userUpload">
        <!-- 文件验证 -->
        <action name="check" class="cn.com.qytx.cbb.org.action.ImportUserAction" method="check">
        </action>
        <!-- 导入 -->
        <action name="importUser" class="cn.com.qytx.cbb.org.action.ImportUserAction" method="importUser">
        </action>

    </package>
   
</struts>


      Action文件内容为:

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import cn.com.qytx.platform.base.action.BaseActionSupport;
import cn.com.qytx.platform.org.domain.GroupInfo;
import cn.com.qytx.platform.org.domain.GroupUser;
import cn.com.qytx.platform.org.domain.UserInfo;
import cn.com.qytx.platform.org.service.IGroup;
import cn.com.qytx.platform.org.service.IGroupUser;
import cn.com.qytx.platform.org.service.IUser;
import cn.com.qytx.platform.utils.encrypt.MD5;
import cn.com.qytx.platform.utils.pinyin.Pinyin4jUtil;

/**
 * 
 * <br/>功能: 人员导入
 * <br/>版本: 1.0
 * <br/>开发人员: 潘博
 * <br/>创建日期: 2013-4-11
 * <br/>修改日期: 2013-4-11
 * <br/>修改列表:
 */
public class ImportUserAction extends BaseActionSupport {
    protected static final Logger LOGGER = Logger.getLogger(ImportUserAction.class.getName());
    private static final long serialVersionUID = 1L;
    private File fileToUpload;
    private String uploadFileName;//设置上传文件的文件名
    private String uploadContentType;//上传文件的类型
    private String radioType;//导入类型
    private String file;//上传的文件
    private int allNum = 0;//总个数
    private int successNum = 0;//成功个数
    private int skipNum = 0;//跳过个数
    private int errorNum = 0;//跳过个数
    private int overrideNum = 0;//覆盖个数
    private List<UserInfo> errorUserList=new ArrayList<UserInfo>();
    private String errorFile;
    /**用户信息*/
    @Resource(name = "userService")
    IUser userService;
    /**
     * 部门,群组管理接口
     */
    @Resource(name = "groupService")
    private IGroup groupService;
    
    /**部门人员信息*/
    @Resource(name = "groupUserService")
    IGroupUser groupUserService;

    /**
     * 检查文件是否符合格式action
     *
     * @return
     * @throws Exception
     */
    public String check() throws Exception {

        PrintWriter writer = null;
        try {
            if (uploadFile()) {
                String result = checkExcel(file);
                writer = new PrintWriter(this.getResponse().getWriter());
                writer.print(result);
                writer.close();
            }

        } catch (Exception e) {
            LOGGER.error(e);
            writer = new PrintWriter(this.getResponse().getWriter());
            writer.print("对不起!导入文件时出错!");
            writer.close();
        }
        return null;
    }


    /**
     * 导入人员action
     */
    public String importUser() throws Exception {


        PrintWriter writer = null;
        try {
            if (uploadFile()) {
                String result = startImportUser(file);
                writer = new PrintWriter(this.getResponse().getWriter());
                if (allNum > 0) {
                    int failNum = allNum - successNum - skipNum - overrideNum;//失败条数
                    if (failNum < 0) {
                        failNum = 0;
                    }
                    String path = this.getRequest().getContextPath();
                    String basePath = getRequest().getScheme() + "://" + getRequest().getServerName() + ":" + getRequest().getServerPort() + path + "/";

                    result = "共" + allNum + "行数据,导入成功" + (successNum) + "行,失败" + failNum + "行";
                    if(errorFile!=null && !errorFile.equals(""))
                    {
                        result = "共" + allNum + "行数据,导入成功" + (successNum) + "行,失败" + failNum + "行,  <a href='"+basePath+"/tempfiles/"+errorFile+"'>点击下载失败文件"+"</a>";

                    }
                }
                writer.print(result);
                writer.close();
            }

        } catch (Exception e) {
            LOGGER.error(e);
            writer = new PrintWriter(this.getResponse().getWriter());
            writer.print("对不起!导入文件时出错!");
            writer.close();
        }
        return null;
    }

    /**
     * 上传文件
     */
    private boolean uploadFile() {
        String path = ServletActionContext.getRequest().getRealPath("/upload");
        File checkPath = new File(path);
        if (!checkPath.exists()) {
            //目录不存在,则创建目录
            boolean result = checkPath.mkdirs();
            if (!result){
                return false;
            }
        }
        try {
            if (fileToUpload != null) {
                String fileName = UUID.randomUUID().toString();
                String ext = ".xls";
                if (uploadFileName != null) {
                    ext = uploadFileName.substring(uploadFileName.lastIndexOf("."));
                }
                if (!ext.equals(".xls")) {
                    return false;
                }
                String saveFileName = fileName + ext;
                File savefile = new File(new File(path), saveFileName);
                if (!savefile.getParentFile().exists()){
                    boolean result = savefile.getParentFile().mkdirs();
                    if (!result){
                        return false;
                    }
                }
                    
                FileUtils.copyFile(fileToUpload, savefile);//拷贝文件
                file = path + "/" + saveFileName;

            }

        } catch (Exception e) {

            return false;
        }
        return true;
    }

    /**
     * 判断文件是否符合要求
     *
     * @param excel
     * @return 空字符串表示验证成功 其他失败
     * @throws Exception
     */
    private String checkExcel(String excel) {
        Workbook wb = null;
        String result = "";
        try {
            Integer companyId=0;
            Object obj=getSession().getAttribute("adminUser");
            if(obj!=null){
            	UserInfo loginUser=(UserInfo)obj;
            	companyId=loginUser.getCompanyId();
            }
            InputStream is = new FileInputStream(excel);
            wb = Workbook.getWorkbook(is);
            if(wb==null)
            {
                result="要导入的文件不正确!";
                return result;
            }
            Sheet sheet = wb.getSheet("通讯录");    //获取工作Excel
            if(sheet==null)
            {
                result="要导入的文件不正确!";
                return result;
            }
            boolean flag = true;
            int totalRow=sheet.getRows();
            if(totalRow==1)
            {
                result="请填写要导入的内容!";
                return result;
            }
            //得到列的长度
            Cell[] cellsZero = sheet.getRow(0);    //读标题行
            Integer headLength=cellsZero.length;
            //第一行不判断
            for (int j = 1; j < sheet.getRows(); j++) {
                Cell[] cells = sheet.getRow(j);    //读取一行
                // 如果这行全部为空,则不处理
                boolean isEmpty = true;
                if(cells!=null){
                for (Cell cell : cells)
                {
                    String val = cell.getContents();// 内容
                    if (null != val && !"".equals(val.trim()))
                    {
                        isEmpty = false;
                        break;
                    }
                }
                }
                if (isEmpty)
                {
                    continue;
                } 
                
                if(cells!=null&&cells.length<headLength){
                    result = "第" + (j + 1) + "行数据不完整!";
                    break;
                }
                if (cells != null && cells.length > 0) {
                    for (int k = 0; k < cells.length; k++) {

                        String val = cells[k].getContents();//内容
                        if (val != null) {
                            val = val.trim();
                        }
                      if (k == 0) {
                            //判断姓名
                            if (val == null || val.equals("")) {
                                result = "第" + (j + 1) + "行第" + (k + 1) + "列姓名不能为空!";
                                flag = false;//退出循环
                                break;
                            } else {
                                if (val.length() > 20) {
                                    result = "第" + (j + 1) + "行第" + (k + 1) + "列姓名长度不能大于20!";
                                    flag = false;//退出循环
                                    break;
                                }
                            }
                        } else if (k == 1) {
                            //判断部门
                            if (val == null || val.equals("")) {
                                result = "第" + (j + 1) + "行第" + (k + 1) + "列部门不能为空!";
                                flag = false;//退出循环
                                break;
                            } else {
                                if (val.length() > 30) {
                                    result = "第" + (j + 1) + "行第" + (k + 1) + "列部门长度不能大于30!";
                                    flag = false;//退出循环
                                    break;
                                }else{
                                	//判断部门是否存在
                                	GroupInfo  groupInfoVO=groupService.loadGroupByPathName(companyId, val);
                                	if(groupInfoVO==null){
                                        result = "第" + (j + 1) + "行第" + (k + 1) + "列部门("+val+")不存在!";
                                        flag = false;//退出循环
                                        break;
                                	}
                                }
                            }
                        } else if (k == 2) {
                            //判断性别
                            if (val != null && !"".equals(val)){
                                if(!("男".equals(val) || "女".equals(val))){
                                    result = "第" + (j + 1) + "行第" + (k + 1) + "列性别填写错误!";
                                    flag = false;//退出循环
                                    break;
                                }
                            }
                        }else if (k == 3) {
                            //判断移动电话1
                            if (val == null || val.equals("")) {
                                result = "第" + (j + 1) + "行第" + (k + 1) + "列联系电话不能为空!";

                                flag = false;//退出循环
                                break;
                            } else {
                                if (!CheckUtil.isNumeric(val)) {
                                    result = "第" + (j + 1) + "行第" + (k + 1) + "列联系电话格式不正确,应该为11位手机号码!";
                                    flag = false;//退出循环
                                    break;
                                } else if (val.length() != 11) {
                                    result = "第" + (j + 1) + "行第" + (k + 1) + "列联系电话格式不正确,应该为11位手机号码!";
                                    flag = false;//退出循环
                                    break;
                                }
                            }
                        }
                    }//column
                }
                if (!flag) {
                    break;
                }
            }//one sheet

        } catch (Exception ex) {
            result = ex.getMessage();
        } finally {
            if (wb != null) {
                wb.close();
            }
        }
        return result;
    }

    /**
     * 开始导入人员
     *
     * @param excel
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
	private String startImportUser(String excel) throws Exception {
        UserInfo adminUser = (UserInfo) this.getSession().getAttribute("adminUser");
        String check = checkExcel(excel);
        if (!check.equals("")) {
            return check;
        } else {
            List<UserInfo> userList=getUserList(excel);
            if(userList!=null && userList.size()>0)
            {
                allNum=userList.size();//总个数
                
                Integer companyId=0;
                Object obj=getSession().getAttribute("adminUser");
                if(obj!=null){
                	UserInfo loginUser=(UserInfo)obj;
                	companyId=loginUser.getCompanyId();
                }
                for(UserInfo user:userList)
                {
	                  //开始导入人员
	            	  try{
	            	   //填充未设置字段           
	                   //根据部门名称得到部门代码
	                   Integer groupId=0;
	                   GroupInfo  groupInfoVO=groupService.loadGroupByPathName(companyId, user.getGroupName());
	                   if(groupInfoVO!=null){
	                	   groupId=groupInfoVO.getGroupId();
	                	   user.setGroupId(groupId);
	                   }else{
	                       errorNum++;
	                       break;
	                   }
	                   
	                 //群组
//	                   int count = groupUserService.getUsersCountByGroupId(groupId);
	                   
	                   // 判断是否重复
	                   UserInfo  oldUserInfo = userService.getUserByNamePhone(adminUser.getCompanyId(), user.getUserName(), user.getPhone());
	                   if (null != oldUserInfo)
	                   {
//	                	  //群组删除olduser
//	                	   List<GroupUser> groupUsers =groupUserService.getGroupUserByUserId(oldUserInfo.getUserId());
	                      //群组end
	                	   groupUserService.deleteGroupUserByUserIds(oldUserInfo.getUserId().toString());
	                	   oldUserInfo.setGroupId(groupInfoVO.getGroupId());
	                	   // 性别
                           oldUserInfo.setSex( user.getSex()!=null? user.getSex():0);
	                       //添加部门/群众人员对应关系
                           GroupUser gu=new GroupUser();
                           gu.setGroupId(groupInfoVO.getGroupId());
                           gu.setUserId(oldUserInfo.getUserId());
                           gu.setCompanyId(adminUser.getCompanyId());
                           groupUserService.saveOrUpdate(gu);
                           
                           userService.saveOrUpdate(oldUserInfo);
                           successNum++;
	                       continue;
	                   }
	                   
	                   //登录密码默认123456
	                   MD5 md5=new MD5();
	                   String pass=md5.encrypt("123456");
	                   user.setIsDelete(0);
	                   user.setLoginPass(pass);
	                   user.setCompanyId(adminUser.getCompanyId());
	                   // 默认设置用户未配置登录信息
	                   user.setLoginName(UUID.randomUUID().toString());
	                   user.setUserState(UserInfo.USERSTATE_UNLOGIN);
	                   SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	                 //  user.setRegisterTime(new Date());
	                   user.setCreateTime(new Date());
	                   String py=Pinyin4jUtil.getPinYinHeadChar(user.getUserName());
	                   user.setPy(py);
	                   user.setOrderIndex(9999);
	                   user.setSkinLogo(1);
	                   user.setIsDefault(1);
	                   user.setTaoDa(0);
	                   user.setOfficeWidget(0);
	                   user.setSinWidget(0);
	                   userService.saveOrUpdate(user);
	                   if(user.getUserId()>0){
		                   //添加部门/群众人员对应关系
		                   GroupUser gu=new GroupUser();
		                   gu.setGroupId(groupId);
		                   gu.setUserId(user.getUserId());
		                   gu.setCompanyId(companyId);
		                   groupUserService.saveOrUpdate(gu);
	                   }
	                   successNum++;
	                   
	            	  }catch (Exception e) {
	            		  errorUserList.add(user);
	            	  }finally{
	            		  
	            	  }
	            	
                }
            }
        }
        return "";
    }
    /**
     * 由文件生成用户列表
     * @param excel
     * @return
     */
    private List<UserInfo> getUserList(String excel)
    {
        List<UserInfo> list =new ArrayList<UserInfo>();
        Workbook wb = null;
        try
        {
            InputStream is = new FileInputStream(excel);
            wb = Workbook.getWorkbook(is);
            Sheet sheet = wb.getSheet("通讯录");    //获取工作Excel
            boolean flag = true;
            //第一行不判断
            for (int j = 1; j < sheet.getRows(); j++) {

                Cell[] cells = sheet.getRow(j);    //读取一行
                if (cells != null && cells.length > 0) {
                	UserInfo user=new UserInfo();
                	String loginName="";//用户名
                    String userName="";//姓名
                    String groupName="";//部门名称
                    String sex="";//性别
                    String phone="";//手机
                    for (int k = 0; k < cells.length; k++) {
                        String val = cells[k].getContents();//内容
                        if (val != null) {
                            val = val.trim();
                        }
                        if (k == 0) {
                            userName=val;
                        }else if (k == 1) {
                            groupName=val;
                        }else if (k == 2) {
                            sex=val;
                        }else if (k == 3) {
                            phone=val;
                        }
                    }//column
                    user.setLoginName(loginName);
                    user.setUserName(userName);
                    user.setGroupName(groupName);
                    user.setPhone(phone);
                    if (!StringUtils.isEmpty(sex)){
                        if("女".equals(sex)){
                            user.setSex(0);
                        }else{
                            user.setSex(1);
                        }
                    }
                    list.add(user);
                }
                if (!flag) {
                    break;
                }
            }//one sheet

        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            LOGGER.error(ex);
        }
        finally {
            if(wb!=null)
            {
                wb.close();
            }
        }
        return list;
    }
    /**
     * 替换掉str里面的特殊字符
     * @param str
     * @return
     */
    private static String stringFilter(String str){
        String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
        Pattern p   =   Pattern.compile(regEx);
        Matcher m   =   p.matcher(str);
        return m.replaceAll("").trim();
    }
    public File getFileToUpload() {
        return fileToUpload;
    }

    public void setFileToUpload(File fileToUpload) {
        this.fileToUpload = fileToUpload;
    }

    public String getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String getUploadContentType() {
        return uploadContentType;
    }

    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }

    public String getRadioType() {
        return radioType;
    }

    public void setRadioType(String radioType) {
        this.radioType = radioType;
    }

}

完毕。希望大家指教。。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值