ASP.NET EXCEL导入,身份证、手机号长度校验数据校验


            
                
批量导入
  
<%----%>
#region 批量导入相关
        /// 
        /// 批量导入按钮
        /// 
        /// 
        /// 
        protected void btnBathAdd_Click(MiniButton sender, AjaxActionEventArgs e)
        {
            this.wpWin.JSShowAtPos(XAlign.center, YAlign.middle);
            fileUpload.JSClear();

            UploadeEntity item = new UploadeEntity();
            fileForm.JSSetData(item);
        }

        //下载样表
        protected void lbExportModule_Click(WuhanIns.Web.MiniUI.LinkButton sender, AjaxActionEventArgs e)
        {
            WriteToExcel();
            this.JSCallMethod("downTemplate", "");
        }
        //导入
        protected void btnBathImport_Click(MiniButton sender, AjaxActionEventArgs e)
        {
            //上传前判断是否存在相同的更新包
            this.fileUpload.JSStartUpload();
        }

        [FormPostBack("fileForm")]
        protected void fileUpload_CustomAction(MiniControl sender, AjaxCustomEventArgs e)
        {
            UploadeEntity FormData = e.GetRequestParam("fileForm");
            string fileName = "";
            if (FormData != null)
            {
                fileName = FormData.fileName;
            }
            if (e.ActionType == "uploadsuccess")
            {
                //上传成功
                UploadeEntity item = new UploadeEntity();
                item.ErrMsg = "上传成功!";
                if (Session["FILE_UP_ERR_MGS"] != null && Session["FILE_UP_ERR_MGS"].ToString() != "")
                {
                    item.ErrMsg = Session["FILE_UP_ERR_MGS"].ToString();
                }
                fileForm.JSSetData(item);
                dgList.JSLoadData();
            }
            else if (e.ActionType == "uploaderror")
            {
                string strMgs = "文件上传失败!";
                this.JSAlert(strMgs);
            }
            else if (e.ActionType == "uploadcomplete")
            {
                //文件上传完成
                this.JSShowTips("上传完成!");
            }
        }

        /// 
        /// Excel导入事件【1、将excel上传至服务器并生成datatable 2、校验datatable中数据 3、保存数据至db中】
        /// 
        /// 
        /// 
        protected void fileUpload_Upload(WuhanIns.Web.MiniUI.FileUpload sender, FileUploadEventArgs e)
        {
            #region
            StringBuilder strErr = new StringBuilder();
            //IDbConnection sqlCon = DBUtil.GetDbConnection();
            //IDbTransaction sqlTrans = sqlCon.BeginTransaction();
            try
            {
                Session["FILE_UP_ERR_MGS"] = "";
                if (string.IsNullOrEmpty(e.PostFile.FileName)) return;

                HttpPostedFile httpFile = e.PostFile;
                string curProjectId = EntityIdSessionConfig.GetCurEntityIdSession(this, EntityIdSessionConfig.Project_Id);
                //string curProjectId = e.GetRequestParam("Project_Id");
                string strAddress = Server.MapPath("TempFiles");
                if (!Directory.Exists(strAddress)) //如果文件夹不存在则创建
                {
                    Directory.CreateDirectory(strAddress);
                }
                //保存数据包到服务器
                string descFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + httpFile.FileName;
                string strFullAddress = Server.MapPath("TempFiles") + "\\" + descFileName;
                httpFile.SaveAs(strFullAddress);//将excel保存至服务器
                DataSet ds = ExcelInput(strFullAddress);//Excel转换DataTable
                //获取所有的分包商信息
                List> htSuppliers = GetSuppliers();
                //获取所属部门
                //Hashtable ht = GetDept();
                //获取工作岗位或者工种,
                //Hashtable htWork = GetProjectWork();
                //获取发放方式
                IdTextItem[] payWaylist = IdTextItem.ToItems(typeof(EPC发放方式));

                //获取发放方式
                IdTextItem[] positionNamelist = IdTextItem.ToItems(typeof(工种));
                //获取身份证hashtable,
                List> sfzhtWork = GetIdCardHt();
                int irowIndex = 1;
                //默认本部门人员
                string deptid = UserContext.CurrentUser.DeptId;
                string deptName = UserContext.CurrentUser.DeptName;
                //身份证列表
                List idCardList = new List();
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        #region 遍历datatable
                        irowIndex++;

                        #region 数据校验,构造数据
                        string identityCard = dr["身份证号码"] == DBNull.Value ? "" : dr["身份证号码"].ToString().Trim();
                        if (string.IsNullOrEmpty(identityCard))
                        {
                            strErr.Append("第" + irowIndex + "行【身份证号码】未填写!\r\n");
                            //continue;
                        }
                        if (identityCard.Length != 15 && identityCard.Length != 18)
                        {
                            strErr.Append("第" + irowIndex + "行【身份证号码】格式不正确!\r\n");
                            //continue;
                        }
                        if ((identityCard.Length == 15 && !CheckIDCard15(identityCard)) || (identityCard.Length == 18 && !CheckIDCard18(identityCard)))
                        {
                            strErr.Append("第" + irowIndex + "行【身份证号码】格式不正确!\r\n");
                            //continue;
                        }
                        else
                        {
                            //身份证验证正确的情况
                            if (idCardList.Contains(identityCard))
                            {
                                strErr.Append("第" + irowIndex + "行【身份证号码】的数据在模板中存在多条!\r\n");
                                //continue;
                            }
                            else
                            {
                                idCardList.Add(identityCard);
                            }
                        }

                        HrStaffBase curData = HrStaffBaseManager.GetByIdCard(identityCard); //根据身份证号查询人员信息
                        //if (curData != null)
                        //{
                        //    curData.DataState = InsSysLib.Core.DataState.Modify;
                        //}
                        //else
                        //{
                        //    curData = new HrStaffBase();
                        //    curData.DataState = InsSysLib.Core.DataState.New;
                        //    curData.Id = Guid.NewGuid().ToString();
                        //    curData.IdentityCard = identityCard;
                        //}
                        if (curData == null)
                        {
                            strErr.Append("第" + irowIndex + "行,用户未采集进场信息,不能导入!\r\n");
                            //continue;
                        }
                        else
                        {
                            if (curData.IdentityCard.Length == 15)
                            {
                                string birth = curData.IdentityCard.Substring(6, 6).Insert(4, "-").Insert(2, "-");
                                curData.Birthday = StrHelper.ParseDate(birth, DateTime.Now);//出生年月
                            }
                            if (curData.IdentityCard.Length == 18)
                            {
                                string birthday = curData.IdentityCard.Substring(6, 4) + "-" + curData.IdentityCard.Substring(10, 2) + "-" + curData.IdentityCard.Substring(12, 2);
                                curData.Birthday = StrHelper.ParseDate(birthday, DateTime.Now);//出生年月
                            }

                            if (curData.Birthday.HasValue)
                                curData.Age = DateTime.Now.Year - curData.Birthday.Value.Year;//年龄
                            if (curData.Age == 0 || curData.Age == null)
                            {
                                strErr.Append("第" + irowIndex + "行【年龄】未填写!\r\n");
                                //continue;
                            }
                            if (string.IsNullOrEmpty(dr["姓名"].ToString()))
                            {
                                strErr.Append("第" + irowIndex + "行【姓名】未填写!\r\n");
                                //continue;
                            }
                            else
                            {
                                curData.Name = dr["姓名"] == DBNull.Value ? "" : dr["姓名"].ToString();
                            }
                            if (string.IsNullOrEmpty(dr["性别"].ToString()))
                            {
                                strErr.Append("第" + irowIndex + "行【性别】未填写!\r\n");
                                //continue;
                            }
                            else
                            {
                                curData.Sex = dr["性别"] == DBNull.Value ? (int)性别.男 : (int)Enum.Parse(typeof(性别), dr["性别"].ToString());
                            }
                            if (!string.IsNullOrEmpty(curData.IdentityCard) && sfzhtWork.Count(x => x.Item2.Contains(dr["身份证号码"].ToString().Trim())) > 0)
                            {
                                curData.Id = sfzhtWork.FirstOrDefault(x => x.Item2.Contains(dr["身份证号码"].ToString().Trim())) == null ? ""
                                    : sfzhtWork.FirstOrDefault(x => x.Item2.Contains(dr["身份证号码"].ToString().Trim())).Item1;
                            }
                            curData.AnmeldenLocationNumber = dr["户口所在地"] == DBNull.Value ? "" : dr["户口所在地"].ToString().Trim();
                            if (string.IsNullOrEmpty(curData.AnmeldenLocationNumber))
                            {
                                strErr.Append("第" + irowIndex + "行【户口所在地】未填写!\r\n");
                                //continue;
                            }
                            if (string.IsNullOrEmpty(dr["学历"].ToString()))
                            {
                                strErr.Append("第" + irowIndex + "行【学历】未填写!\r\n");
                                //continue;
                            }
                            else
                            {
                                curData.EducationalLevel = dr["学历"] == DBNull.Value ? (int)学历.本科 : (int)Enum.Parse(typeof(学历), dr["学历"].ToString());
                            }

                            //人员和项目信息关联
                            curData.ProjectId = curProjectId;
                            if (String.IsNullOrEmpty(curData.SubcontractorId))
                            {
                                strErr.Append("第" + irowIndex + "行【所属分包商】未填写!\r\n");
                                //continue;
                            }
                            else
                            {
                                //所属分包商
                                curData.SubcontractorId = dr["所属分包商"] == DBNull.Value ? "" : htSuppliers.Count(x => x.Item2 == dr["所属分包商"].ToString()) > 0 ? htSuppliers.FirstOrDefault(x => x.Item2 == dr["所属分包商"].ToString()).Item1 : "";
                            }
                            //else
                            //{
                            //    // 判断如果是黑名单,则continue
                            //    var isblacklist = htSuppliers.FirstOrDefault(x => x.Item2 == dr["所属分包商"].ToString()).Item3;
                            //    if (isblacklist == "1")
                            //    {
                            //        strErr.Append("第" + irowIndex + "行【所属分包商】属于黑名单,无法导入!\r\n");
                            //        continue;
                            //    }
                            //}
                            //所属劳务组织
                            //curData.SignDeptId = dr["所属劳务组织"] == DBNull.Value ? "" : htSuppliers.Count(x => x.Item2 == dr["所属劳务组织"].ToString()) > 0 ? htSuppliers.FirstOrDefault(x => x.Item2 == dr["所属劳务组织"].ToString()).Item1 : "";
                            //if (String.IsNullOrEmpty(curData.Sign_dept_id))
                            //{
                            //    strErr.Append("第" + irowIndex + "行【所属劳务组织】未填写!\r\n");
                            //    continue;
                            //}

                            curData.PositionName = dr["工种"] == DBNull.Value ? "" : dr["工种"].ToString();
                            if (!string.IsNullOrEmpty(curData.PositionName))
                            {
                                curData.Position = ((int)Enum.Parse(typeof(工种), dr["工种"].ToString())).ToString();
                            }
                            //curData.Position = dr["工种"] == DBNull.Value ? "" : htWork.ContainsKey(dr["工种"].ToString()) ? htWork[dr["工种"].ToString()].ToString() : "";
                            //curData.Position = dr["工种"] == DBNull.Value ? "" : ((int)Enum.Parse(typeof(工种), dr["工种"].ToString())).ToString();
                            if (string.IsNullOrEmpty(curData.Position))
                            {
                                strErr.Append("第" + irowIndex + "行【工种】未填写!\r\n");
                                //continue;
                            }

                            curData.Seniority = dr["工作年限"] == DBNull.Value ? DBUtil.INVALID_ID : StrHelper.ParseInt(dr["工作年限"].ToString(), DBUtil.INVALID_ID);
                            int outintvalue;
                            if (!string.IsNullOrEmpty(dr["工作年限"].ToString()))
                            {
                                if (!Int32.TryParse(dr["工作年限"].ToString(), out outintvalue))
                                {
                                    strErr.Append("第" + irowIndex + "行【工作年限】格式不正确,请输入整数!\r\n");
                                    //continue;
                                }
                                if (outintvalue < 0)
                                {
                                    strErr.Append("第" + irowIndex + "行【工作年限】格式不正确,请输入正整数!\r\n");
                                    //continue;
                                }
                            }

                            //curData.ComingDate = DateTime.Now;//进场时间默认赋值新增时间
                            //curData.Coming_date = dr["进场时间"] == DBNull.Value ? DBUtil.INVALID_DATE : StrHelper.ParseDate(dr["进场时间"].ToString(), DBUtil.INVALID_DATE);
                            //DateTime outdate;
                            //if (!string.IsNullOrEmpty(dr["进场时间"].ToString()))
                            //{
                            //    if (!DateTime.TryParse(dr["进场时间"].ToString(), out outdate))
                            //    {
                            //        strErr.Append("第" + irowIndex + "行【进场时间】格式不正确,请输入时间格式!\r\n");
                            //        continue;
                            //    }
                            //}
                            //else
                            //{
                            //    strErr.Append("第" + irowIndex + "行【进场时间】未填写!\r\n");
                            //    continue;
                            //}
                            if (payWaylist.Count(x => x.Text == dr["发放方式"].ToString()) > 0)
                            {
                                curData.PayType = Convert.ToInt32(payWaylist.FirstOrDefault(x => x.Text == dr["发放方式"].ToString()).Id);
                            }
                            //curData.BankAccount = dr["银行卡号"] == DBNull.Value ? "" : dr["银行卡号"].ToString().Trim();
                            if (string.IsNullOrEmpty(dr["银行卡号"].ToString()))
                            {
                                strErr.Append("第" + irowIndex + "行【银行卡号】未填写!\r\n");
                                //continue;
                            }
                            else
                            {
                                if (CheckBankAccount(dr["银行卡号"].ToString().Trim()))
                                {
                                    curData.BankAccount = dr["银行卡号"].ToString().Trim();
                                }
                                else
                                {
                                    strErr.Append("第" + irowIndex + "行【银行卡号】格式不正确,请输入16位或19正整数!\r\n");
                                    //continue;
                                }
                            }

                            if (!string.IsNullOrEmpty(dr["是否贫困县"].ToString()))
                            {
                                if (dr["是否贫困县"].ToString() == "是" || dr["是否贫困县"].ToString() == "否")
                                {
                                    curData.Ispoor = string.IsNullOrEmpty(dr["是否贫困县"].ToString()) ? DBUtil.INVALID_ID : (int)Enum.Parse(typeof(InsSysLib.Core.是否状态), dr["是否贫困县"].ToString());
                                }
                                else
                                {
                                    strErr.Append("第" + irowIndex + "行【是否贫困县】格式不正确,请选择是和否!\r\n");
                                    //continue;
                                }
                            }

                            curData.Address = dr["家庭地址"] == DBNull.Value ? "" : dr["家庭地址"].ToString().Trim();
                            curData.EmergencyContact = dr["紧急联系人"] == DBNull.Value ? "" : dr["紧急联系人"].ToString().Trim();
                            if (string.IsNullOrEmpty(dr["紧急联系人电话"].ToString()))
                            {
                                strErr.Append("第" + irowIndex + "行【紧急联系人电话】未填写!\r\n");
                                //continue;
                            }
                            else
                            {
                                if (CheckContactTel(dr["紧急联系人电话"].ToString().Trim()))
                                {
                                    curData.EmergencyContactTel = dr["紧急联系人电话"].ToString().Trim();
                                }
                                else
                                {
                                    strErr.Append("第" + irowIndex + "行【紧急联系人电话】格式不正确,请输入正确格式的电话!\r\n");
                                    //continue;
                                }
                            }
                            curData.ContactRelationship = dr["关系"] == DBNull.Value ? "" : dr["关系"].ToString().Trim();
                            //curData.Occupational = dr["技能资格证"] == DBNull.Value ? "" : dr["技能资格证"].ToString().Trim();


                            #region 护照信息
                            curData.PassportNumber = dr["护照号码"] == DBNull.Value ? "" : dr["护照号码"].ToString().Trim();
                            curData.PassportType = dr["护照类型"] == DBNull.Value ? "" : dr["护照类型"].ToString().Trim();
                            curData.Visanumber = dr["签证编号"] == DBNull.Value ? "" : dr["签证编号"].ToString().Trim();
                            curData.HzPeriod = dr["护照有效期至"] == DBNull.Value ? DBUtil.INVALID_DATE : StrHelper.ParseDate(dr["护照有效期至"].ToString(), DBUtil.INVALID_DATE);
                            DateTime HzPeriod;
                            if (!string.IsNullOrEmpty(dr["护照有效期至"].ToString()))
                            {
                                if (!DateTime.TryParse(dr["护照有效期至"].ToString(), out HzPeriod))
                                {
                                    strErr.Append("第" + irowIndex + "行【护照有效期至】格式不正确,请输入时间格式!\r\n");
                                }
                            }

                            curData.HandlingDate = dr["办理日期"] == DBNull.Value ? DBUtil.INVALID_DATE : StrHelper.ParseDate(dr["办理日期"].ToString(), DBUtil.INVALID_DATE);
                            DateTime HandlingDate;
                            if (!string.IsNullOrEmpty(dr["办理日期"].ToString()))
                            {
                                if (!DateTime.TryParse(dr["办理日期"].ToString(), out HandlingDate))
                                {
                                    strErr.Append("第" + irowIndex + "行【办理日期】格式不正确,请输入时间格式!\r\n");
                                }
                            }

                            curData.DueDate = dr["到期时间"] == DBNull.Value ? DBUtil.INVALID_DATE : StrHelper.ParseDate(dr["到期时间"].ToString(), DBUtil.INVALID_DATE);
                            DateTime DueDate;
                            if (!string.IsNullOrEmpty(dr["到期时间"].ToString()))
                            {
                                if (!DateTime.TryParse(dr["到期时间"].ToString(), out DueDate))
                                {
                                    strErr.Append("第" + irowIndex + "行【到期时间】格式不正确,请输入时间格式!\r\n");
                                }
                            }
                            #endregion

                            #region 特殊证/保险
                            curData.SpecialCerCode = dr["特种作业证编号"] == DBNull.Value ? "" : dr["特种作业证编号"].ToString().Trim();
                            curData.SpecialCerTime = dr["证书有效期"] == DBNull.Value ? DBUtil.INVALID_DATE : StrHelper.ParseDate(dr["证书有效期"].ToString(), DBUtil.INVALID_DATE);
                            DateTime SpecialCerTime;
                            if (!string.IsNullOrEmpty(dr["证书有效期"].ToString()))
                            {
                                if (!DateTime.TryParse(dr["证书有效期"].ToString(), out SpecialCerTime))
                                {
                                    strErr.Append("第" + irowIndex + "行【证书有效期】格式不正确,请输入时间格式!\r\n");
                                }
                            }
                            if (!string.IsNullOrEmpty(dr["特殊工种"].ToString()))
                            {
                                if (dr["特殊工种"].ToString() == "是" || dr["特殊工种"].ToString() == "否")
                                {
                                    curData.IsOperation = string.IsNullOrEmpty(dr["特殊工种"].ToString()) ? DBUtil.INVALID_ID : (int)Enum.Parse(typeof(InsSysLib.Core.是否状态), dr["特殊工种"].ToString());
                                    if (dr["特殊工种"].ToString() == "是")
                                    {
                                        if (string.IsNullOrEmpty(dr["特种作业证编号"].ToString()))
                                        {

                                            strErr.Append("第" + irowIndex + "行【特种作业证编号】未填写,特殊工种此项必填!\r\n");
                                        }
                                        if (string.IsNullOrEmpty(dr["证书有效期"].ToString()))
                                        {

                                            strErr.Append("第" + irowIndex + "行【证书有效期】未填写,特殊工种此项必填!\r\n");
                                        }
                                    }
                                }
                                else
                                {
                                    strErr.Append("第" + irowIndex + "行【特殊工种】格式不正确,请选择是和否!\r\n");
                                }
                            }

                            curData.InsuranceType = dr["保险类型"] == DBNull.Value ? "" : dr["保险类型"].ToString().Trim();
                            curData.InsuranceTime = dr["保险有效期"] == DBNull.Value ? DBUtil.INVALID_DATE : StrHelper.ParseDate(dr["保险有效期"].ToString(), DBUtil.INVALID_DATE);
                            DateTime InsuranceTime;
                            if (!string.IsNullOrEmpty(dr["保险有效期"].ToString()))
                            {
                                if (!DateTime.TryParse(dr["保险有效期"].ToString(), out InsuranceTime))
                                {
                                    strErr.Append("第" + irowIndex + "行【保险有效期】格式不正确,请输入时间格式!\r\n");
                                }
                            }
                            if (!string.IsNullOrEmpty(dr["购买保险"].ToString()))
                            {
                                if (dr["购买保险"].ToString() == "是" || dr["购买保险"].ToString() == "否")
                                {
                                    curData.Insurance = string.IsNullOrEmpty(dr["购买保险"].ToString()) ? DBUtil.INVALID_ID : (int)Enum.Parse(typeof(InsSysLib.Core.是否状态), dr["购买保险"].ToString());
                                    if (dr["购买保险"].ToString() == "是")
                                    {
                                        if (string.IsNullOrEmpty(dr["保险类型"].ToString()))
                                        {
                                            strErr.Append("第" + irowIndex + "行【保险类型】未填写,购买保险此项必填!\r\n");
                                        }
                                        if (string.IsNullOrEmpty(dr["保险有效期"].ToString()))
                                        {
                                            strErr.Append("第" + irowIndex + "行【保险有效期】未填写,购买保险此项必填!\r\n");
                                        }
                                    }
                                }
                                else
                                {
                                    strErr.Append("第" + irowIndex + "行【购买保险】格式不正确,请选择是和否!\r\n");
                                }
                            }
                            #endregion


                            curData.DataState = InsSysLib.Core.DataState.Modify;
                            curData.CurState = (int)EPC人员状态.待进场;
                        }
                        #endregion

                        if (!string.IsNullOrEmpty(strErr.ToString()))
                        {
                            continue;
                        }
                        HrStaffBaseManager.Save(curData);    //保存数据至db中
                        //if (!string.IsNullOrEmpty(curData.Id))
                        //{
                        //    HrStaffBaseManager.Service.Modify(curData.Id, curData, sqlTrans);//修改
                        //}
                        //else
                        //{
                        //    HrStaffBaseManager.Service.Save(curData, sqlTrans);//新增
                        //}
                        #endregion
                    }
                }
                File.Delete(strFullAddress);//删除服务器中当前excel文件,防止占用服务器磁盘存储空间
                Session["FILE_UP_ERR_MGS"] = strErr.ToString();
                //sqlTrans.Commit();
            }
            catch (Exception ex)
            {
                //sqlTrans.Rollback();
                Session["FILE_UP_ERR_MGS"] = ex.Message;
            }
            finally
            {
                //sqlCon.Close();
            }
            #endregion
        }

        #region 校验18位和15位身份证号方法
        /// 
        /// 校验18位位身份证号方法
        /// 
        /// 
        /// 
        private bool CheckIDCard18(string idNumber)
        {
            long n = 0;
            if (long.TryParse(idNumber.Remove(17), out n) == false
                || n < Math.Pow(10, 16) || long.TryParse(idNumber.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证  
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(idNumber.Remove(2)) == -1)
            {
                return false;//省份验证  
            }
            string birth = idNumber.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证  
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = idNumber.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != idNumber.Substring(17, 1).ToLower())
            {
                return false;//校验码验证  
            }
            return true;//符合GB11643-1999标准  
        }
        /// 
        /// 校验15位身份证号方法
        /// 
        /// 
        /// 
        private bool CheckIDCard15(string Id)
        {
            long n = 0; if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14))
            {
                return false;//数字验证 
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;//省份验证 
            }
            string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-"); DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证  
            }
            return true;//符合15位身份证标准 
        }

        #endregion

        #region 校验16位或19位银行卡号
        private bool CheckBankAccount(string BankAccount)
        {
            bool result = false;
            //string regex = @"^\d{16}|\d{19}$";//16至19位数字
            string regex = @"^([0-9]{16}|[0-9]{19})$";//16或19位数字
            Match m = Regex.Match(BankAccount, regex);
            if (m.Success)
            {
                result = true;
            }
            return result;
        }

        private bool CheckContactTel(string ContactTel)
        {
            bool result = false;
            bool result1 = false;
            bool result2 = false;
            //https://c.runoob.com/front-end/854
            string regex1 = @"^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$";//手机号码
            string regex2 = @"\d{3}-\d{8}|\d{4}-\d{7}";//国内电话号码(0511-4405222、021-87888822)
            Match m1 = Regex.Match(ContactTel, regex1);
            if (m1.Success)
            {
                result1 = true;
            }
            Match m2 = Regex.Match(ContactTel, regex2);
            if (m2.Success)
            {
                result2 = true;
            }
            if (result1 || result2)
            {
                result = true;
            }
            return result;
        }
        #endregion

        /// 
        /// Excel转换DataTable
        /// 
        /// 文件的绝对路径
        /// DataTable
        public static DataSet ExcelInput(string FilePath)
        {
            #region xlsx文件
            //DataSet ds = new DataSet();
            根据路径通过已存在的excel来创建XSSFWorkbook,即整个excel文档
            //xlsx文件
            //XSSFWorkbook workbook = new XSSFWorkbook(File.Open(FilePath, FileMode.Open));
            //XSSFSheet sheet = (XSSFSheet)workbook.GetSheetAt(0);
            xls文件
            HSSFWorkbook workbook = new HSSFWorkbook(File.Open(FilePath, FileMode.Open));
            HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(0);

            //DataTable table = new DataTable();
            //table.TableName = sheet.SheetName;
            获取excel的第一个sheet
            获取Excel的最大行数
            //int rowsCount = sheet.PhysicalNumberOfRows;//获取Excel文档中数据不为空行数
            为保证Table布局与Excel一样,这里应该取所有行中的最大列数(需要遍历整个Sheet)。
            为少一交全Excel遍历,提高性能,我们可以人为把第0行的列数调整至所有行中的最大列数。
            int colsCount = sheet.GetRow(1).PhysicalNumberOfCells;//获取Excel文档中数据不为空列数
            //int colsCount = 17;//获取Excel文档导入列数
            //for (int i = 0; i < colsCount; i++)
            //{
            //    table.Columns.Add(sheet.GetRow(1).GetCell(i).ToString());
            //}
            //for (int x = 2; x < rowsCount; x++)
            //{
            //    DataRow dr = table.NewRow();
            //    if (colsCount >= 1)
            //    {
            //        for (int y = 0; y < colsCount; y++)
            //        {
            //            if (sheet.GetRow(x).GetCell(y) != null)
            //                dr[y] = sheet.GetRow(x).GetCell(y).ToString();
            //            else
            //                dr[y] = null;
            //        }
            //    }
            //    table.Rows.Add(dr);
            //}
            //ds.Tables.Add(table);
            //return ds;
            #endregion

            #region xls文件,导出xls文件只有一行标题,导出xlsx文件有两行标题
            DataSet ds = new DataSet();
            //根据路径通过已存在的excel来创建XSSFWorkbook,即整个excel文档
            xlsx文件
            //XSSFWorkbook workbook = new XSSFWorkbook(File.Open(FilePath, FileMode.Open));
            //XSSFSheet sheet = (XSSFSheet)workbook.GetSheetAt(0);
            //xls文件
            HSSFWorkbook workbook = new HSSFWorkbook(File.Open(FilePath, FileMode.Open));
            HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(0);

            DataTable table = new DataTable();
            table.TableName = sheet.SheetName;
            //获取excel的第一个sheet
            //获取Excel的最大行数
            int rowsCount = sheet.PhysicalNumberOfRows;//获取Excel文档中数据不为空行数
            //为保证Table布局与Excel一样,这里应该取所有行中的最大列数(需要遍历整个Sheet)。
            //为少一交全Excel遍历,提高性能,我们可以人为把第0行的列数调整至所有行中的最大列数。
            //int colsCount = sheet.GetRow(1).PhysicalNumberOfCells;//获取Excel文档中数据不为空列数
            int colsCount = 29;//获取Excel文档导入列数 17银行卡号
            for (int i = 0; i < colsCount; i++)
            {
                //table.Columns.Add(sheet.GetRow(1).GetCell(i).ToString());
                table.Columns.Add(sheet.GetRow(0).GetCell(i).ToString());//构造列
            }
            //for (int x = 2; x < rowsCount; x++)
            for (int x = rowsCount - 1; x < rowsCount; x++)//遍历行,构造行数据
            {
                DataRow dr = table.NewRow();
                if (colsCount >= 1)
                {
                    for (int y = 0; y < colsCount; y++)//构造列数据
                    {
                        //if (sheet.GetRow(x).GetCell(y) != null)
                        //    dr[y] = sheet.GetRow(x).GetCell(y).ToString();
                        //else
                        //    dr[y] = null;


                        if (sheet.GetRow(x).GetCell(y) != null)
                        {
                            ICell cellItem = sheet.GetRow(x).GetCell(y);//获取当前单元格
                            if (cellItem.CellType == NPOI.SS.UserModel.CellType.Numeric && DateUtil.IsCellDateFormatted(cellItem))//当前单元格类型为Numeric,且为日期格式时转换单元格内容格式,防止导入异常
                            {
                                //dr[y] = cellItem.DateCellValue.ToString("yyyy/MM/dd");
                                dr[y] = cellItem.DateCellValue.ToString("yyyy-MM-dd");
                            }
                            else
                            {
                                dr[y] = sheet.GetRow(x).GetCell(y).ToString();
                            }
                        }
                        else
                            dr[y] = null;
                    }
                }
                table.Rows.Add(dr);
            }
            ds.Tables.Add(table);
            return ds;
            #endregion
        }

        private XSSFWorkbook xssfworkbook;

        /// 
        /// 下载excel模板
        /// 
        public void DownloadExcel()
        {
            string fileName = "人员台账模板.xlsx";
            string sServerPath = Server.MapPath("TempFiles") + "\\" + fileName;//Server.MapPath(fileName);

            FileInfo file = new FileInfo(sServerPath);
            FileStream myFile = File.OpenRead(sServerPath);
            byte[] byteData = new byte[myFile.Length];
            myFile.Read(byteData, 0, (int)myFile.Length);
            // byte[] byteData = data.Data;
            HttpResponse response = HttpContext.Current.Response;
            response.Clear();
            response.ClearContent();
            response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(file.Name));
            response.AddHeader("Content-Length", byteData.Length.ToString());
            response.AddHeader("Content-Transfer-Encoding", "binary");
            //response.ContentType = contentType;
            response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            response.BinaryWrite(byteData);
            response.Flush();
            response.End();
            //File.Delete(sServerPath);
        }

        /// 
        /// 写入Excel 设置数据源
        /// 
        public void WriteToExcel()
        {
            if (!Directory.Exists(Server.MapPath("TempFiles")))
            {
                Directory.CreateDirectory(Server.MapPath("TempFiles"));
            }

            //生成的下载Excel
            string sDownLoadServerPath = Server.MapPath("TempFiles") + "\\" + "人员台账模板.xlsx";

            //原始Excel
            string fileName = "TempFiles/人员台账模板1.xlsx";
            string sServerPath = Server.MapPath(fileName);
            FileStream myFile = File.OpenRead(sServerPath);
            FileStream file = new FileStream(sServerPath, FileMode.Open, FileAccess.Read);
            xssfworkbook = new XSSFWorkbook(file);
            ISheet sheet = xssfworkbook.GetSheet("数据源");
            IRow row = null;
            //查询list
            //人员分类
            //var personList = CommonTypeCache.ListCommonTypeByDefCode(ConstuctionCommonType.人员分类, true);
            //岗位
            //var gangweilist = new List();
            //List entities = RangeCache.QueryProjectWorkerForCache(null, new OrderByParams("Inner_Code"));
            //foreach (CacheObject entity in entities)
            //{
            //    gangweilist.Add(new TreeListItem { Id = entity.Id, Text = "[" + entity.OuterCode + "]" + entity.Name });
            //}
            //人员种类
            var gongzhonglist = IdTextItem.ToItems(typeof(工种));
            人员状态
            //var personStatelist = IdTextItem.ToItems(typeof(EPC人员状态));
            //是否
            var Isfalselist = IdTextItem.ToItems(typeof(是否));
            //性别
            var Issexlist = IdTextItem.ToItems(typeof(性别));
            //学历
            var studylist = IdTextItem.ToItems(typeof(学历));

            //发放方式
            var payWaylist = IdTextItem.ToItems(typeof(EPC发放方式));

            //所属单位
            //var deptlist = new List();
            //所属分包商
            List ht = GetSupplierIdTextList();
            //string sCompanyId = UserContext.CurrentUser.CompanyId;
            //OrgQueryParams queryParam = new OrgQueryParams();
            //queryParam.OrgPartType = OrgPartEnum.内部单位;
            //queryParam.IsRecursive = true;
            //List _items = SystemServiceFactory.Service.GetOrgAncestors(sCompanyId);
            //foreach (TreeListItem item in _items)
            //{
            //    if (string.IsNullOrEmpty(item.ParentId))
            //        queryParam.RootOrgId = item.Id;
            //}
            //queryParam.OrgType = OrgTypeEnum.全部;
            //queryParam.AppendRootNode = true;
            //deptlist = SystemServiceFactory.Service.GetOrganizationList(UserContext.CurrentUser.CurrentAppID, queryParam);
            //List items1 = SystemServiceFactory.Service.GetAllUpperOutCompy(sCompanyId, true);
            //deptlist.AddRange(items1);

            var maxCountList = new List{  //gangweilist.Count(),//personList.Count(),deptlist.Count, personStatelist.Count(),
                gongzhonglist.Count(),Isfalselist.Count(), studylist.Count(), ht.Count,payWaylist.Count() };
            var maxNum = Convert.ToInt32(maxCountList.OrderByDescending(x => x).FirstOrDefault().ToString());
            for (int i = 0; i < maxNum; i++)
            {
                row = sheet.CreateRow(i + 1);
                var countindex = i;
                row.CreateCell(0).SetCellValue(ht.Count > countindex ? (ht[countindex] == null ? "" : ht[countindex].Text) : "");
                row.CreateCell(1).SetCellValue(gongzhonglist.Count() > countindex ? (gongzhonglist[countindex] == null ? "" : gongzhonglist[countindex].Text) : "");
                row.CreateCell(2).SetCellValue(Issexlist.Count() > countindex ? (Issexlist[countindex] == null ? "" : Issexlist[countindex].Text) : "");
                row.CreateCell(3).SetCellValue(payWaylist.Count() > countindex ? (payWaylist[countindex] == null ? "" : payWaylist[countindex].Text) : "");
                row.CreateCell(4).SetCellValue(studylist.Count() > countindex ? (studylist[countindex] == null ? "" : studylist[countindex].Text) : "");
                //row.CreateCell(5).SetCellValue(studylist.Count() > countindex ? (studylist[countindex] == null ? "" : studylist[countindex].Text) : "");
                //row.CreateCell(6).SetCellValue(Issexlist.Count() > countindex ? (Issexlist[countindex] == null ? "" : Issexlist[countindex].Text) : "");
                //row.CreateCell(7).SetCellValue(deptlist.Count > countindex ? (deptlist[countindex] == null ? "" : deptlist[countindex].Text) : "");
                //rowCount++;
            }
            sheet.ForceFormulaRecalculation = true;
            file = new FileStream(sDownLoadServerPath, FileMode.Create);
            xssfworkbook.Write(file);
            file.Close();
            file.Dispose();
        }

        / 
        / 初始化Excel
        / 
        / 
        //public void InitWorkbook(FileStream stream)
        //{
        //    xssfworkbook = new HSSFWorkbook(stream);

        //    DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
        //    dsi.Company = "Ins lnc";
        //    xssfworkbook.DocumentSummaryInformation = dsi;

        //    SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
        //    si.Subject = "人员台帐";
        //    xssfworkbook.SummaryInformation = si;
        //}


        /// 
        /// 设置选择源区域
        /// 
        /// 数据区sheet
        /// 数据区对应的选择项列
        /// 源sheet
        /// 源对应的列编号名
        /// 源起始行
        /// 源结束行
        public void SetChongeSource(ref ISheet sheet, int colIndex, string sSheetName, string letter, int startRowIndex, int endRowIndex, string dicRange)
        {
            CellRangeAddressList rangeList = new CellRangeAddressList(1, 1000, colIndex, colIndex);

            HSSFName range = (HSSFName)xssfworkbook.CreateName();
            range.RefersToFormula = sSheetName + "!$" + letter + "$" + startRowIndex + ":$" + letter + "$" + endRowIndex;
            range.NameName = dicRange;

            DVConstraint dvconstraint = DVConstraint.CreateFormulaListConstraint(dicRange);
            HSSFDataValidation dataValidation = new HSSFDataValidation(rangeList, dvconstraint);
            ((HSSFSheet)sheet).AddValidationData(dataValidation);
        }


        /// 
        /// 初始化源sheet
        /// 
        /// 当前sheet
        /// sheet编号
        /// sheet名称
        public void InitSheet(ref ISheet currentSheet, int sheetIndex, string sSheetName)
        {
            try
            {
                currentSheet = xssfworkbook.GetSheetAt(sheetIndex);
            }
            catch { }
            if (currentSheet != null)
            {
                xssfworkbook.RemoveSheetAt(sheetIndex);
            }
            currentSheet = xssfworkbook.CreateSheet(sSheetName);
            xssfworkbook.SetSheetHidden(sheetIndex, true);
        }

        #region 导出样表下拉数据源
        //所属单位
        protected Hashtable GetDept()
        {
            string sCompanyId = UserContext.CurrentUser.CompanyId;
            List items = new List();
            OrgQueryParams queryParam = new OrgQueryParams();
            queryParam.OrgPartType = OrgPartEnum.内部单位;
            queryParam.IsRecursive = true;
            List _items = SystemServiceFactory.Service.GetOrgAncestors(sCompanyId);
            foreach (TreeListItem item in _items)
            {
                if (string.IsNullOrEmpty(item.ParentId))
                    queryParam.RootOrgId = item.Id;
            }

            queryParam.OrgType = OrgTypeEnum.全部;
            queryParam.AppendRootNode = true;
            items = SystemServiceFactory.Service.GetOrganizationList(UserContext.CurrentUser.CurrentAppID, queryParam);

            List items1 = SystemServiceFactory.Service.GetAllUpperOutCompy(sCompanyId, true);

            items.AddRange(items1);

            Hashtable ht = new Hashtable();
            int d = 0;
            foreach (TreeListItem t in items)
            {
                if (t.Text != null && !ht.ContainsKey(t.Text))
                {
                    ht.Add(t.Text, t.Id);
                }

            }
            return ht;
        }

        //人员分类
        private Hashtable GetCommonType()
        {
            TreeListItem[] listItems = CommonTypeCache.ListCommonTypeByDefCode(ConstuctionCommonType.人员分类, false); // (ConstuctionCommonType.人员分类);
            Hashtable ht = new Hashtable();
            foreach (TreeListItem t in listItems)
            {
                if (t.Text != null && !ht.ContainsKey(t.Text))
                {
                    ht.Add(t.Text, t.Id);
                }
            }
            return ht;
        }

        //岗位或工种
        //private Hashtable GetProjectWork()
        //{
        //    List entities = RangeCache.QueryProjectWorkerForCache(null, new OrderByParams("Inner_Code"));
        //    Hashtable ht = new Hashtable();
        //    foreach (CacheObject entity in entities)
        //    {
        //        if (entity.Name != null && !ht.ContainsKey(entity.Name))
        //        {
        //            ht.Add("[" + entity.OuterCode + "]" + entity.Name, entity.Id);
        //        }
        //    }
        //    return ht;
        //}

        //id和身份证
        private List> GetIdCardHt()
        {
            //HrStaffBaseParams ps = new HrStaffBaseParams();
            //ps.Deleted = 0;
            //ps.Project_id = string.IsNullOrEmpty(curProjectId) ? "-1" : curProjectId;  不根据项目来了。包含已退场的其他项目的
            var idcardlist = new List>();
            var HrStaffBase = HrStaffBaseManager.Find(true);//(ps, null, null);
            foreach (HrStaffBase entity in HrStaffBase)
            {
                if (entity.IdentityCard != null)
                {
                    var item = new Tuple(entity.Id, entity.IdentityCard);
                    idcardlist.Add(item);
                }
            }
            return idcardlist;
        }



        //其他枚举
        private Hashtable GetEnumData(Type type)
        {
            Hashtable ht = new Hashtable();
            foreach (int myCode in Enum.GetValues(type))
            {
                string strName = Enum.GetName(type, myCode);//获取名称
                string strVaule = myCode.ToString();//获取值
                if (!ht.ContainsKey(strName))
                {
                    ht.Add(strName, strVaule);
                }
            }
            return ht;
        }

        //其他枚举(排序用)
        private Hashtable GetEnumData2(Type type)
        {
            Hashtable ht = new Hashtable();
            foreach (int myCode in Enum.GetValues(type))
            {
                string strName = Enum.GetName(type, myCode);//获取名称
                string strVaule = myCode.ToString();//获取值
                if (!ht.ContainsKey(strName))
                {
                    ht.Add(strVaule, strName);
                }
            }
            return ht;
        }

        /// 
        /// 获取分包商信息
        /// 
        /// 
        private List> GetSuppliers()
        {
            #region
            //List> ht = new List>();
            SupplierBaseInfoParams supplierPs = new SupplierBaseInfoParams();
            supplierPs.Sup_type = (int)是否状态.是;
            string sProjectId = EntityIdSessionConfig.GetCurEntityIdSession(EntityIdSessionConfig.Project_Id);
            if (!AppConfigUtil.isEnterprise)
                supplierPs.Project_id = sProjectId;
            else
            {
                SqlComplexParam sql = new SqlComplexParam(" t.PROJECT_ID IS NULL");
                supplierPs.AppendChild(sql);
            }
            //List baseInfos = SupplierBaseInfoManager.Find(true);// Service.QueryIDOsByParams(supplierPs, null, null);
            //if (baseInfos != null && baseInfos.Count() > 0)
            //{
            //    foreach (SupplierBaseInfo entity in baseInfos)
            //    {
            //        ht.Add(new Tuple(entity.Id, entity.Supplier_name, entity.Isblacklist.ToString()));
            //    }
            //}
            //return ht;
            #endregion

            #region
            List> ht = new List>();
            List baseInfos = HrSubcontractorManager.Find(true);
            if (baseInfos != null && baseInfos.Count() > 0)
            {
                foreach (SubcontractorBase entity in baseInfos)
                {
                    ht.Add(new Tuple(entity.Id, entity.SubcontractorName, entity.Isblacklist.ToString()));
                }
            }
            return ht;
            #endregion
        }

        /// 
        /// 获取分包商列表
        /// 
        /// 
        private List GetSupplierIdTextList()
        {
            #region
            //List list = new List();
            SupplierBaseInfoParams supplierPs = new SupplierBaseInfoParams();
            supplierPs.Sup_type = (int)是否状态.是;
            //string sProjectId = EntityIdSessionConfig.GetCurEntityIdSession(EntityIdSessionConfig.Project_Id);
            if (!AppConfigUtil.isEnterprise)
                supplierPs.Project_id = sProjectId;
            else
            {
                SqlComplexParam sql = new SqlComplexParam(" t.PROJECT_ID IS NULL");
                supplierPs.AppendChild(sql);
            }
            //List baseInfos = SupplierBaseInfoManager.GetSuppliersByType(sProjectId, (int)InsSysLib.Core.是否状态.是);//.Service.QueryIDOsByParams(supplierPs, null, null);
            //if (baseInfos != null && baseInfos.Count() > 0)
            //{
            //    foreach (SupplierBaseInfo entity in baseInfos)
            //    {
            //        list.Add(new IdTextItem { Id = entity.Id, Text = entity.Supplier_name });
            //    }
            //}
            //return list;
            #endregion

            #region
            List list = new List();
            string sProjectId = EntityIdSessionConfig.GetCurEntityIdSession(EntityIdSessionConfig.Project_Id);
            List baseInfos = HrSubcontractorManager.Find(true);
            if (baseInfos != null && baseInfos.Count() > 0)
            {
                foreach (SubcontractorBase entity in baseInfos)
                {
                    list.Add(new IdTextItem { Id = entity.Id, Text = entity.SubcontractorName });
                }
            }
            return list;
            #endregion
        }

        / 
        / 设置数据源(按照值排序)
        / 
        / 源选项名称。例如:所属单位
        / 数据源
        / 填充到数据源sheet中的列号
        //public int SetCellDataSource2Sort(string datasourcename, Hashtable ht, int colindex, string sheetname)
        //{
        //    //任务类型标题
        //    ISheet Sheet2 = xssfworkbook.GetSheet(sheetname);
        //    if (Sheet2 == null)
        //    {
        //        Sheet2 = xssfworkbook.CreateSheet();
        //    }
        //    //源选项名称。例如:所属单位
        //    IRow row = Sheet2.GetRow(0);
        //    if (row == null)
        //    {
        //        row = Sheet2.CreateRow(0);
        //    }
        //    row.CreateCell(colindex).SetCellValue(datasourcename);
        //    //添加空白项。
        //    IRow row2 = Sheet2.GetRow(1);
        //    if (row2 == null)
        //    {
        //        row2 = Sheet2.CreateRow(1);
        //    }
        //    row2.CreateCell(colindex).SetCellValue("");
        //    int i = 2;
        //    ArrayList alv = new ArrayList(ht.Keys);
        //    alv.Sort();
        //    foreach (object obj in alv)
        //    {
        //        IRow curRow = Sheet2.GetRow(i);
        //        if (curRow == null)
        //        {
        //            curRow = Sheet2.CreateRow(i);
        //        }
        //        curRow.CreateCell(colindex).SetCellValue(ht[obj].ToString());
        //        i++;
        //    }

        //    return ht.Count + 2;
        //}

        #endregion

        #endregion

 

你可能感兴趣的:(Asp.Net)