ASP.NET Excel文件导入

    protected void btnImport_Click(object sender, EventArgs e)
    {
        string path;
        string errorMsg;
        if (Upload(out path,out errorMsg))
        {
            string extend = path.Substring(path.LastIndexOf("."));
            string conn;
            if (extend == ".xls")
            {
                conn = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
            }
            else
            {
                conn = "Provider=Microsoft.ACE.OleDb.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=YES'";
            }

            string sql = "select * from [学生表$]";
            OleDbCommand cmd = new OleDbCommand(sql, new OleDbConnection(conn));
            OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
            adapter.Fill(dt);
            string info;
            if (ImportSql(dt, out info))
            {
                DeleteFile(path);
                this.gvStudentsList.DataSource = students;
                this.gvStudentsList.DataBind();
                this.lblInfo.Text = info;
            }
            else
            {
                DeleteFile(path);
                this.lblInfo.Text = info;
            }
        }
        else
        {
            DeleteFile(path);
            this.lblInfo.Text = "errorMsg";
        }
    }

   
    //文件上传
    protected bool Upload(out string path, out string errorMsg)
    {
        int maxRequestLength = Convert.ToInt32(configManager.GetMaxRequestLength());

        if (fileUp.HasFile)
        {
            if (fileUp.PostedFile.ContentLength <= maxRequestLength * 1024 * 1024)
            {
                string type = fileUp.PostedFile.ContentType;
                string extName = fileUp.FileName.Substring(fileUp.FileName.LastIndexOf(".")).ToLower();
                if ((type == "text/xml" || type == "application/vnd.ms-excel" || type == "application/octet-stream") && new string[2] { ".xls", ".xlsx" }.Contains(extName))
                {
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmssms") + extName;
                    string savePath = Server.MapPath("~/UpFile/" + fileName);
                    fileUp.SaveAs(savePath);
                    path = savePath;
                    errorMsg = "";
                    return true;
                }
                else
                {
                    errorMsg = "<font color='red'>上传的文件类型或者后缀名不是excel文件</font>";
                }
            }
            else
            {
                errorMsg = "<font color='red'>上传文件大小的超过系统上限</font>";
            }
        }
        else
        {
            errorMsg = "<font color='red'>请选择要上传文件</font>";
        }
        path = "";
        return false;
    }

    //导入数据库
    protected bool ImportSql(DataTable dt, out string info)
    {
        if (dt.Rows.Count == 0)
        {
            info = "<font color='red'>上传的文件不包含学生信息</font>";
            return false;
        }

        int number = 1;

        try
        {
          

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                StudentInfo student = new StudentInfo();

                //检测序列号是否为空或非整数
                try
                {
                    number = Convert.ToInt32(dt.Rows[i][0].ToString().Trim());
                }
                catch (Exception)
                {
                    info = string.Format("<font color='red'>第{0}行数据的序号为空或为非整型,导入失败</font>", i + 1);
                    return false;
                }

                #region
                //检测学号
                if (dt.Rows[i][1] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][1].ToString().Trim()) && dt.Rows[i][1].ToString().Trim().Length <= 50)
                {
                    foreach (KeyValuePair<string, string> item in noList)
                    {
                        if (item.Value == dt.Rows[i][1].ToString().Trim())
                        {
                            info = string.Format("<font color='red'>序号为{0}和{1}的行的学生具有相同的学号,导入失败</font>", item.Key, number);
                            return false;
                        }
                    }
                    //保存当前行的序列号和学生学号,便于后面的比较
                    noList.Add(dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString().Trim());
                    if (studentManager.IsExistNO(dt.Rows[i][1].ToString().Trim()))
                    {
                        info = string.Format("<font color='red'>序号为:{0}的学生的学号在数据库中已经存在,导入失败</font>", number);
                        return false;
                    }
                    student.NO = dt.Rows[i][1].ToString().Trim();//学号保存到对象中
                }
                else
                {
                    info = string.Format("<font color='red'>序号为{0}的学生\"学号\"列数据不能为空且不能超过50,导入失败</font>", number);
                    return false;
                }

                //检查学生姓名列
                if (dt.Rows[i][2] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][2].ToString().Trim()) && dt.Rows[i][2].ToString().Trim().Length <= 20)
                {
                    student.Name = dt.Rows[i][2].ToString().Trim();
                }
                else
                {
                    info = string.Format("<font color='red'>序号为{0}的学生的\"姓名\"列数据不能为空且不能超过20,导入失败</font>", number);
                    return false;
                }

                //检查学生性别列
                if (dt.Rows[i][3] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][3].ToString().Trim()))
                {
                    if (dictionaryManager.GetDictionaryByGroupName("Sex").Select(p => p.Content == dt.Rows[i][3].ToString().Trim()).ToList().Count < 1)
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"性别\"列数据不是模板提供的数据,导入失败</font>", number);
                        return false;

                    }
                    int sex = dictionaryManager.GetDicIdByContent(dt.Rows[i][3].ToString().Trim(), "Sex");
                    if (sex != -1)
                        student.Sex = sex;
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"性别\"列数据不是模板提供的数据,导入失败</font>", number);
                        return false;
                    }
                }
                else
                {
                    info = string.Format("<font color='red'>序号为{0}的学生的\"性别\"列数据不能为空,导入失败</font>", number);
                    return false;
                }

                //检查学生民族列(可以为空)
                if (dt.Rows[i][4] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][4].ToString().Trim()))//假如不是null
                {
                    if (dictionaryManager.GetDictionaryByGroupName("Nation").Select(p => p.Content == dt.Rows[i][4].ToString().Trim()).ToList().Count < 1)
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"民族\"列数据不是模板提供的数据,导入失败</font>", number);
                        return false;
                    }
                    int nation = dictionaryManager.GetDicIdByContent(dt.Rows[i][4].ToString().Trim(), "Nation");
                    if (nation != -1)
                        student.Nation = nation;
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"民族\"列数据不是模板提供的数据,导入失败</font>", number);
                        return false;
                    }
                }
                else//假如是null赋个初始值58,汉族
                {
                    student.Nation = 58;
                }

                //检查政治面貌列
                if (dt.Rows[i][5] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][5].ToString().Trim()))
                {
                    if (dictionaryManager.GetDictionaryByGroupName("PoliticsStatus").Select(p => p.Content == dt.Rows[i][5].ToString().Trim()).ToList().Count < 1)
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"政治面貌\"列数据不是模板提供的数据,导入失败</font>", number);
                        return false;
                    }
                    int politicsStatus = dictionaryManager.GetDicIdByContent(dt.Rows[i][5].ToString().Trim(), "PoliticsStatus");
                    if (politicsStatus != -1)
                        student.PoliticsStatus = politicsStatus;
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"政治面貌\"列数据不是模板提供的数据,导入失败</font>", number);
                        return false;
                    }
                }
                else//假如是null赋个初始值62,群众
                {
                    student.PoliticsStatus = 62;
                }

                //检查生源地
                if (dt.Rows[i][6] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][6].ToString().Trim()))
                {
                    if (dt.Rows[i][6].ToString().Trim().Length <= 200)
                        student.NativePlace = dt.Rows[i][6].ToString().Trim();
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"生源地\"列数据长度不能超过200,导入失败</font>", number);
                        return false;
                    }
                }
                else
                {
                    student.NativePlace = "";
                }

                //检查身份证号列
                if (dt.Rows[i][7] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][7].ToString().Trim()) && dt.Rows[i][7].ToString().Trim().Length <= 100)
                {
                    //检查身份证是否是合法的身份证(格式)
                    if (!new Regex(@"^\d{17}[\d|X]$|^\d{15}$").IsMatch(dt.Rows[i][7].ToString().Trim()))
                    {
                        info = string.Format("<font color='red'>序号为:{0}的学生的身份证号不是正确格式,导入失败</font>", number);
                        return false;
                    }
                    //学号在当前excel中是否有重复
                    foreach (KeyValuePair<string, string> item in idnoList)
                    {
                        if (item.Value == dt.Rows[i][7].ToString().Trim())
                        {
                            info = string.Format("<font color='red'>序号为{0}和{1}的行的学生具有相同的身份证号,导入失败</font>", item.Key, number);
                            return false;
                        }
                    }
                    //记录当前行的序列号和学生身份证号,便于后面的比较
                    idnoList.Add(dt.Rows[i][0].ToString().Trim(), dt.Rows[i][7].ToString().Trim());
                    //身份证号在数据库中是否已经存在
                    if (studentManager.IsExistIDNO(dt.Rows[i][7].ToString().Trim()))
                    {
                        info = string.Format("<font color='red'>序号为:{0}的学生的身份证号在数据库中已经存在,导入失败</font>", number);
                        return false;
                    }
                    student.IDNO = dt.Rows[i][7].ToString().Trim();//身份证保存到对象中
                }
                else
                {
                    info = string.Format("<font color='red'>序号为{0}的学生\"身份证号\"列数据不能为空,导入失败</font>", number);
                    return false;
                }

                //检查专业班级列
                if (dt.Rows[i][8] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][8].ToString().Trim()) && dt.Rows[i][8].ToString().Trim().Length <= 100)
                {
                    student.ClassName = dt.Rows[i][8].ToString().Trim();
                }
                else
                {
                    info = string.Format("<font color='red'>序号为{0}的学生的\"专业班级\"列数据不能为空且长度不能超过100,导入失败</font>", number);
                    return false;
                }

                //检查手机号列
                if (dt.Rows[i][9] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][9].ToString().Trim()))
                {
                    if (dt.Rows[i][9].ToString().Trim().Length <= 20)
                    {
                        if (new Regex(@"^(1[358]\d{9})?$").IsMatch(dt.Rows[i][9].ToString().Trim()))
                        {
                            student.Phone = dt.Rows[i][9].ToString().Trim();
                        }
                        else
                        {
                            info = string.Format("<font color='red'>序号为{0}的学生的\"手机号\"列数据不是手机号,导入失败</font>", number);
                            return false;
                        }
                    }
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"手机号\"列数据长度不能超过20,导入失败</font>", number);
                        return false;
                    }
                }
                else
                {
                    student.Phone = "";
                }

                //检查备用手机号
                if (dt.Rows[i][10] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][10].ToString().Trim()))
                {
                    if (dt.Rows[i][10].ToString().Trim().Length <= 20)
                    {
                        if (new Regex(@"^(1[358]\d{9})?$").IsMatch(dt.Rows[i][10].ToString().Trim()))
                        {
                            student.Phone2 = dt.Rows[i][10].ToString().Trim();
                        }
                        else
                        {
                            info = string.Format("<font color='red'>序号为{0}的学生的\"备用手机号\"列数据不是手机号,导入失败</font>", number);
                            return false;
                        }
                    }
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"备用手机号\"列数据长度不能超过20,导入失败</font>", number);
                        return false;
                    }
                }
                else
                {
                    student.Phone2 = "";
                }

                //家庭电话
                if (dt.Rows[i][11] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][11].ToString().Trim()))
                {
                    if (dt.Rows[i][11].ToString().Trim().Length <= 20)
                    {
                        if (new Regex(@"(^1[358]\d{9}$)|(^0\d{2,3}-\d{7,8}(-\d{1,4})?$)").IsMatch(dt.Rows[i][11].ToString().Trim()))
                        {
                            student.HomePhone = dt.Rows[i][11].ToString().Trim();
                        }
                        else
                        {
                            info = string.Format("<font color='red'>序号为{0}的学生的\"家庭电话\"列数据不是正确的联系方式,导入失败</font>", number);
                            return false;
                        }
                    }
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"家庭电话\"列数据长度不能超过20,导入失败</font>", number);
                        return false;
                    }
                }
                else
                {
                    student.HomePhone = "";
                }

                //家庭邮编
                if (dt.Rows[i][12] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][12].ToString().Trim()))
                {
                    if (dt.Rows[i][12].ToString().Trim().Length <= 10)
                    {
                        if (new Regex(@"^\d{6}$").IsMatch(dt.Rows[i][12].ToString().Trim()))
                        {
                            student.PostalCode = dt.Rows[i][12].ToString().Trim();
                        }
                        else
                        {
                            info = string.Format("<font color='red'>序号为{0}的学生的\"家庭邮编\"列数据不是手机号,导入失败</font>", number);
                            return false;
                        }
                    }
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"家庭邮编\"列数据长度不能超过20,导入失败</font>", number);
                        return false;
                    }
                }
                else
                {
                    student.PostalCode = "";
                }

                //通讯地址
                if (dt.Rows[i][13] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][13].ToString().Trim()))
                {
                    if (dt.Rows[i][13].ToString().Trim().Length <= 200)
                        student.PostalAddress = dt.Rows[i][13].ToString().Trim();
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"通讯地址\"列数据长度不能超过200,导入失败</font>", number);
                        return false;
                    }
                }
                else
                {
                    student.PostalAddress = "";
                }

                //检查家庭收件人列
                if (dt.Rows[i][14] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][14].ToString().Trim()))
                {
                    if (dt.Rows[i][14].ToString().Trim().Length <= 20)
                        student.HomeLinkman = dt.Rows[i][14].ToString().Trim();
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"家庭收件人\"列数据长度不能超过20,导入失败</font>", number);
                        return false;
                    }
                }
                else
                {
                    student.HomeLinkman = "";
                }

                //检查现所在地列
                if (dt.Rows[i][15] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][15].ToString().Trim()))
                {
                    if (dt.Rows[i][15].ToString().Trim().Length <= 20)
                        student.NowLocal = dt.Rows[i][15].ToString().Trim();
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"现所在地\"列数据长度不能超过20,导入失败", number);
                        return false;
                    }
                }
                else
                {
                    student.NowLocal = "";
                }

                //检查住宿情况列
                if (dt.Rows[i][16] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][16].ToString().Trim()))
                {
                    //添加学生时,学生住住宿情况只能是提供的两个选项,也不能是"在寝",要实现"在寝"必须要通话分配寝室功能实现
                    if (dictionaryManager.GetDictionaryByGroupName("StayStatus").Select(p => p.Content == dt.Rows[i][16].ToString().Trim() && p.Content != "在寝").ToList().Count < 1)
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"住宿情况\"列数据不是模板提供的数据,导入失败", number);
                        return false;
                    }
                    int stayStatus = dictionaryManager.GetDicIdByContent(dt.Rows[i][16].ToString().Trim(), "StayStatus");
                    if (stayStatus != -1)
                        student.StayStatus = stayStatus;
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"住宿情况\"列数据不是模板提供的数据,导入失败", number);
                        return false;
                    }
                }
                else
                {
                    info = string.Format("<font color='red'>序号为{0}的学生的\"住宿情况\"列数据不能为空,导入失败", number);
                    return false;
                }

                //检查就业情况列
                if (dt.Rows[i][17] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][17].ToString().Trim()))
                {
                    if (dictionaryManager.GetDictionaryByGroupName("JobStatus").Select(p => p.Content == dt.Rows[i][17].ToString().Trim()).ToList().Count < 1)
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"就业情况\"列数据不是模板提供的数据,导入失败", number);
                        return false;
                    }
                    int jobStatus = dictionaryManager.GetDicIdByContent(dt.Rows[i][17].ToString().Trim(), "JobStatus");
                    if (jobStatus != -1)
                        student.JobStatus = jobStatus;
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"就业情况\"列数据不是模板提供的数据,导入失败", number);
                        return false;
                    }
                }
                else//假如是null赋个初始值65,未就业
                {
                    student.JobStatus = 65;
                }

                //检查工作单位列
                if (dt.Rows[i][18] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][18].ToString().Trim()))
                {
                    if (dt.Rows[i][18].ToString().Trim().Length <= 50)
                        student.Company = dt.Rows[i][18].ToString().Trim();
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"工作单位\"列数据长度不能超过50,导入失败", number);
                        return false;
                    }
                }
                else
                {
                    student.Company = "";
                }

                //检查单位地址列
                if (dt.Rows[i][19] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][19].ToString().Trim()))
                {
                    if (dt.Rows[i][19].ToString().Trim().Length <= 200)
                        student.CompanyAddress = dt.Rows[i][19].ToString().Trim();
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"单位地址\"列数据长度不能超过200,导入失败", number);
                        return false;
                    }
                }
                else
                {
                    student.CompanyAddress = "";
                }

                //检查单位联系人
                if (dt.Rows[i][20] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][20].ToString().Trim()))
                {
                    if (dt.Rows[i][20].ToString().Trim().Length <= 20)
                        student.CompanyLinkman = dt.Rows[i][20].ToString().Trim();
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"单位联系人\"列数据长度不能超过20,导入失败", number);
                        return false;
                    }
                }
                else
                {
                    student.CompanyLinkman = "";
                }

                //检查单位联系电话
                if (dt.Rows[i][21] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][21].ToString().Trim()))
                {

                    if (dt.Rows[i][21].ToString().Trim().Length <= 20)
                    {
                        if (new Regex(@"^(1[358]\d{9})?$|^(0\d{2,3}-\d{7,8})?$").IsMatch(dt.Rows[i][21].ToString().Trim()))
                        {
                            student.CompanyPhone = dt.Rows[i][21].ToString().Trim();
                        }
                        else
                        {
                            info = string.Format("<font color='red'>序号为{0}的学生的\"单位联系电话\"列数据不是正确格式号码,导入失败", number);
                            return false;
                        }
                    }
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"单位联系电话\"列数据长度不能超过20,导入失败", number);
                        return false;
                    }
                }
                else
                {
                    student.CompanyPhone = "";
                }

                //检查三方协议书列
                if (dt.Rows[i][22] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][22].ToString().Trim()))
                {
                    if (dictionaryManager.GetDictionaryByGroupName("TripartiteAgreement").Select(p => p.Content == dt.Rows[i][22].ToString().Trim()).ToList().Count < 1)
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"三方协议书\"列数据不是模板提供的数据,导入失败", number);
                        return false;
                    }
                    int tripartiteAgreement = dictionaryManager.GetDicIdByContent(dt.Rows[i][22].ToString().Trim(), "TripartiteAgreement");
                    if (tripartiteAgreement != -1)
                        student.TripartiteAgreement = tripartiteAgreement;
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"三方协议书\"列数据不是模板提供的数据,导入失败", number);
                        return false;
                    }
                }
                else//假如是null赋个初始值72,未签
                {
                    student.TripartiteAgreement = 72;
                }

                //检查工作地点列
                if (dt.Rows[i][23] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][23].ToString().Trim()))
                {
                    if (dictionaryManager.GetDictionaryByGroupName("WorkingPlace").Select(p => p.Content == dt.Rows[i][23].ToString().Trim()).ToList().Count < 1)
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"工作地点\"列数据不是模板提供的数据,导入失败", number);
                        return false;
                    }
                    int workingPlace = dictionaryManager.GetDicIdByContent(dt.Rows[i][23].ToString().Trim(), "WorkingPlace");
                    if (workingPlace != -1)
                        student.WorkingPlace = workingPlace;
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"工作地点\"列数据不是模板提供的数据,导入失败", number);
                        return false;
                    }
                }
                else//假如是null赋个初始值96,未定
                {
                    student.WorkingPlace = 96;
                }

                //检查备注列
                if (dt.Rows[i][24] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i][24].ToString().Trim()))
                {
                    if (dt.Rows[i][24].ToString().Trim().Length <= 500)
                        student.Remarks = dt.Rows[i][24].ToString().Trim();
                    else
                    {
                        info = string.Format("<font color='red'>序号为{0}的学生的\"备注\"列数据长度不能超过500,导入失败", number);
                        return false;
                    }
                }
                else
                {
                    student.Remarks = "";
                }
                #endregion
                SqlParameter[] pars = { new SqlParameter("@NO", student.NO), new SqlParameter("@Name", student.Name), new SqlParameter("@Sex", student.Sex), new SqlParameter("@Nation", student.Nation), new SqlParameter("@PoliticsStatus", student.PoliticsStatus), new SqlParameter("@NativePlace", student.NativePlace), new SqlParameter("@IDNO", student.IDNO), new SqlParameter("@ClassName", student.ClassName), new SqlParameter("@Phone", student.Phone), new SqlParameter("@Phone2", student.Phone2), new SqlParameter("@HomePhone", student.HomePhone), new SqlParameter("@PostalCode", student.PostalCode), new SqlParameter("@PostalAddress", student.PostalAddress), new SqlParameter("@HomeLinkman", student.HomeLinkman), new SqlParameter("@NowLocal", student.NowLocal), new SqlParameter("@StayStatus", student.StayStatus), new SqlParameter("@JobStatus", student.JobStatus), new SqlParameter("@Company", student.Company), new SqlParameter("@CompanyAddress", student.CompanyAddress), new SqlParameter("@CompanyLinkman", student.CompanyLinkman), new SqlParameter("@CompanyPhone", student.CompanyPhone), new SqlParameter("@TripartiteAgreement", student.TripartiteAgreement), new SqlParameter("@WorkingPlace", student.WorkingPlace), new SqlParameter("@Remarks", student.Remarks) };
                listPars.Add(pars);
                students.Add(student);  
            }

            if (studentManager.ImportStudent(listPars))
            {
                info = string.Format("<font color='green'>导入成功</font>");
                return true;
            }
            else
            {
                info = string.Format("<font color='red'>导入异常,请稍后再试</font>");
                return false;
            }
        }
        catch (Exception)
        {
            info = string.Format("<font color='red'>导入异常,请稍后再试</font>");
            return false;
        }
    }

    //删除上传的文件
    protected void DeleteFile(string path)
    {
        if (File.Exists(path))
        {
            File.Delete(path);
        }
    }

服务类方法:

/// <summary>
        /// 批量导入学生信息
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public bool ImportStudent(List<SqlParameter[]> param)
        {
            bool b = false;
            string sql = "up_AddStudent";
            Dictionary<string, List<SqlParameter[]>> dic = new Dictionary<string, List<SqlParameter[]>>();
            dic.Add(sql, param);
            if (helper.BatchExecuteTran(dic))
            {
                b = true;
            }
            return b;
        }

 

DBHelper类方法:

public bool BatchExecuteTran(Dictionary<string, List<SqlParameter[]>> dic)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = this.Conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Transaction = cmd.Connection.BeginTransaction();

            try
            {
                foreach (var item in dic)
                {
                    cmd.CommandText = item.Key;

                    if (item.Value != null)
                    {
                        foreach (SqlParameter[] item1 in item.Value)
                        {
                            cmd.Parameters.Clear();
                            if (item1 != null)
                            {
                                cmd.Parameters.AddRange(item1);
                            }
                            cmd.ExecuteNonQuery();
                        }
                    }
                }

                cmd.Transaction.Commit();
                return true;
            }
            catch (Exception)
            {
                cmd.Transaction.Rollback();
                return false;
            }
            finally
            {
                cmd.Connection.Close();
            }

        }

存储过程

up_AddStudent

CREATE PROCEDURE up_AddStudent(
           @NO varchar(50),
           @Name varchar(20),
           @Sex int,
           @Nation int,
           @PoliticsStatus int,
           @NativePlace varchar(200),
           @IDNO varchar(100),
           @ClassName varchar(100),
           @Phone varchar(20),
           @Phone2 varchar(20),
           @HomePhone varchar(20),
           @PostalCode varchar(10),
           @PostalAddress varchar(200),
           @HomeLinkman varchar(20),
           @NowLocal varchar(20),
           @StayStatus int,
           @JobStatus int,
           @Company varchar(50),
           @CompanyAddress varchar(200),
           @CompanyLinkman varchar(20),
           @CompanyPhone varchar(20),
           @TripartiteAgreement int,
           @WorkingPlace int,
           @Remarks varchar(500)
           )
AS
BEGIN
declare @UserId int
begin tran
 insert into  [SystemUsers] ([LoginId],[LoginPWD],[State],[LastLoginTime],[UserType])
 values (@NO,@NO,89,GETDATE(),94)
 if @@error<>0
 begin
  goto Error
 end
 select @UserId=@@identity
 insert into [Students] ([UserId],[NO],[Name],[Sex],[Nation],[PoliticsStatus],[NativePlace],[IDNO],[ClassName],[Phone],[Phone2],[HomePhone],[PostalCode],[PostalAddress],[HomeLinkman],[NowLocal],[StayStatus],[JobStatus],[Company],[CompanyAddress],[CompanyLinkman],[CompanyPhone],[TripartiteAgreement],[WorkingPlace],[Remarks])
 values (@UserId,@NO,@Name,@Sex,@Nation,@PoliticsStatus,@NativePlace,@IDNO,@ClassName,@Phone,@Phone2,@HomePhone,@PostalCode,@PostalAddress,@HomeLinkman,@NowLocal,@StayStatus,@JobStatus,@Company,@CompanyAddress,@CompanyLinkman,@CompanyPhone,@TripartiteAgreement,@WorkingPlace,@Remarks)
 if @@error<>0
 begin
  goto Error
 end
  
goto Suess
Error:
rollback tran
return
Suess:
commit tran
END

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值