コード例 #1
0
    protected void btnUplaodExcel_Click(object sender, EventArgs e)
    {
        if (fuploadExcel.PostedFile == null)
        {
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "key5", "ShowAlert('danger','Please select the file again');", true);
            return;
        }
        string[] validFileTypes = { "xlsx", "xls" };
        string   ext            = System.IO.Path.GetExtension(fuploadExcel.PostedFile.FileName);
        bool     isValidFile    = false;

        for (int i = 0; i < validFileTypes.Length; i++)
        {
            if (ext.ToUpper() == "." + validFileTypes[i].ToUpper())
            {
                isValidFile = true;
                break;
            }
        }

        if (!isValidFile)
        {
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "key6", "ShowAlert('danger','Invalid File.');", true);
            return;
        }
        string filepath = Path.Combine(System.Configuration.ConfigurationManager.AppSettings["MigrationTempFiles"].ToString(), fuploadExcel.FileName); //Server.MapPath("MigrationTempFiles/") + fuploadExcel.FileName;

        fuploadExcel.PostedFile.SaveAs(filepath);
        if (System.IO.File.Exists(filepath))
        {
            int Departmentid = 0;
            using (SessionService sser = new SessionService())
            {
                Departmentid = sser.CurrentUser.DepartmentId;
            }

            ExcelImporter excel = new ExcelImporter();

            System.Data.DataTable dtData = excel.ReadandUpload(filepath);
            using (EmployeeService empser = new EmployeeService())
            {
                string msg    = "";
                string alert  = "";
                bool   retVal = empser.MigrateExcelFileData(dtData, Departmentid, ref msg);
                if (msg != "")
                {
                    string[] arr = msg.Split('$');
                    foreach (string s in arr)
                    {
                        alert += (s + "<br/>");
                    }
                }

                if (retVal)
                {
                    if (msg == "")
                    {
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "key7", "ShowAlert('success','File Uploaded Successfully.');", true);
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "key7", "ShowAlertExcel('success','File Uploaded Successfully but " + alert + "');", true);
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "key8", "ShowAlertExcel('danger','UnExpected Error has occured.Please check the file contents.');", true);
                }
            }
        }
        FillUserList();
    }