1. 程式人生 > >as.net MVC模式 匯入EXCEL文件

as.net MVC模式 匯入EXCEL文件

<%  using (Html.BeginForm("XXX", "Account", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {%>
        <div class="content">
        <label  >請選擇要匯入的資料檔案:</label> <input type="file" name="FileUpload1" /> 
        <input type="submit" name="Submit" id="Submit" value="確定" />
    </div>
    
    <% }%>
    <%if (ViewData["ErrorMsg"] != null)
      { %>
      <div class="content" style="color:Red"><%=ViewData["ErrorMsg"].ToString()%></div>
      <%} %>
        <table class="content">
            <tr>
                <td style="border-bottom:1px solid #bdd2ed; border-right:1px solid #bdd2ed;border-top:1px solid #bdd2ed;">
                    XX名
                </td>
                <td style="border-bottom:1px solid #bdd2ed; border-right:1px solid #bdd2ed;border-top:1px solid #bdd2ed;">
                    是否成功
                </td>
                <td style="border-bottom:1px solid #bdd2ed; border-right:1px solid #bdd2ed;border-top:1px solid #bdd2ed;">
                    說明
                </td>
            </tr>
            <% if (ViewData["returnUserInfo"] != null)
               {
                   List<GTA.MS.NNU.Web.XH.Models.BatchOpenUM_UserInfo> retnInfo = (List<GTA.MS.NNU.Web.XH.Models.BatchOpenUM_UserInfo>)ViewData["returnUserInfo"];
                   foreach (var item in retnInfo)
                   { 
            %>
            <tr>
                <td  style="border-bottom:1px solid #bdd2ed; border-right:1px solid #bdd2ed;">
                    <%: Html.Label( item.LoginName) %>
                </td>
                <td  style="border-bottom:1px solid #bdd2ed; border-right:1px solid #bdd2ed;">
                    <%: Html.Label( item.IsSuccess?"成功":"失敗")%>
                </td>
                <td  style="border-bottom:1px solid #bdd2ed; border-right:1px solid #bdd2ed;">
                    <%: Html.Label( item.Message)%>
                </td>
            </tr>
            <%  }%>
            <%  } %>
        </table> 



        #region Oledb方式讀取EXCEL
        /// <summary>
        /// Oledb方式讀取EXCEL
        /// </summary>
        /// <param name="fileNamePath">檔案路徑</param>
        /// <returns></returns>
        private DataTable ReadExcelByOledb(string fileNamePath)
        {
            string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;data source=" + fileNamePath;
//只讀第一個表
            OleDbConnection oledbconn1 = new OleDbConnection(connStr);
            oledbconn1.Open();
            DataTable _table = oledbconn1.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

            string strTableName = string.Empty;
            if (_table.Rows.Count > 0)
            {
                strTableName = _table.Rows[0]["TABLE_NAME"].ToString().Trim();
                string sql = string.Format("SELECT * FROM [{0}]", strTableName);
                _table = new DataTable();
                OleDbDataAdapter da = new OleDbDataAdapter(sql, oledbconn1);
                da.Fill(_table);
            }
            oledbconn1.Close();
            return _table;
        }
        #endregion

  
        public ActionResult BatchAddAccount()
        {
            return View();
        }

        [RequiresAuthenticationAttribute]
        [HttpPost]
        public ActionResult BatchAddAccount(object obj)
        {
            string error = string.Empty;
            List<BatchOpenUserInfo> returnUserInfo = new List<BatchOpenUserInfo>();
            ViewData["returnUserInfo"] = returnUserInfo;
            ViewData["ErrorMsg"] = "";
            DataTable contactTable; 
            try
            {
                foreach (string upload in Request.Files)
                {
                    if (upload != null && upload.Trim() != "")
                    {
                        string path = AppDomain.CurrentDomain.BaseDirectory + "TempData\\";
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        System.Web.HttpPostedFileBase postedFile = Request.Files[upload];
                        string filename = Path.GetFileName(postedFile.FileName);
                        if (filename.Length > 4)
                        {
                            string strExName = filename.Substring(filename.Length - 4, 4);
                            if (strExName.ToLower() != ".xls")
                            {
                                error = "檔案型別不正確,請重新操作";
                                ViewData["ErrorMsg"] = error;
                                //return View();
                            }
                            else
                            {
                                //string filePath = Path.Combine(path, filename);
                                string fileNamePath = path + DateTime.Now.Ticks.ToString() + ".xls";
                                postedFile.SaveAs(fileNamePath);

                                string fileExtension;
                                fileExtension = System.IO.Path.GetExtension(filename);
                                string FileType = postedFile.ContentType.ToString();//獲取要上傳的檔案型別,驗證檔案頭  

                                //在上傳檔案不為空的情況下,驗證檔名以及大小是否符合,如果不符合則不允許上傳
                                if (postedFile.ContentLength / 1024 <= 5120)
                                { //在這裡通過檢查檔案頭與檔名是否匹配 從而限制了檔案上傳型別  注:可上傳的型別有XLS,且大小隻能為5M一下
                                     
                                    contactTable = ReadExcelByOledb(fileNamePath);
                                    int i = contactTable.Rows.Count;
                                    bool success = true;
                                    string msg = string.Empty;
                                    UserInfo userInfo;

                                    List<ProfessionClass> ProfessionList = GetAllProfession();
                                    List<ProfessionClass> ClassList =  GetAllProfession();
                                    if (contactTable.Rows.Count > 1000)
                                    {
                                        error = "匯入資料不能大於1000條!";
                                        ViewData["ErrorMsg"] = error;
                                    }
                                    else
                                    {
                                        foreach (DataRow item in contactTable.Rows)
                                        {
                                            userInfo = new Management.BLL.Common.Model.UM_UserInfo();
                                            success = CheckValue(item[0], CheckType.StringEnChNumber, 20, 0, out msg, "登入名");
                                            if (success) { success = CheckValue(item[1], CheckType.StringEnNumber, 20, 0, out msg, "密碼"); }
                                            if (success) { success = CheckValue(item[2], CheckType.StringEnChNumber, 16, 0, out msg, "專業"); }
                                            if (success) { success = CheckValue(item[3], CheckType.StringEnChNumber, 16, 0, out msg, "班級"); }
                                            
                                            userInfo.LoginName = item[0].ToString();
                                            if (success)
                                            {
                                                userInfo.Password = item[1].ToString();
                                                userInfo.ProfessionalID = FindProfessionIdByName(ProfessionList, item[2].ToString());
                                                userInfo.ClassID = FindClassIdByName(ClassList, item[3].ToString());
                                                if (userInfo.ProfessionalID == 0)
                                                {
                                                    msg = "系統中不存在此專業:" + item[2].ToString() + "!";
                                                    success = false;
                                                }
                                                else
                                                {
                                                    if (userInfo.ClassID == 0)
                                                    {
                                                        msg = "系統中不存在此班級:" + item[3].ToString() + "!";
                                                        success = false;
                                                    }
                                                    else
                                                    {
                                                        success = CreateAccount(userInfo, out msg);
                                                    }
                                                }
                                            }
                                            returnUserInfo.Add(new BatchOpenUserInfo()
                                            {
                                                LoginName = userInfo.LoginName,
                                                IsSuccess = success,
                                                Message = msg
                                            });
                                        }
                                    } 
                                }
                                else
                                {
                                    error = "資料檔案過大,請重新操作";
                                    ViewData["ErrorMsg"] = error;
                                    //return View();
                                }
                            }
                        }
                        else
                        {
                            error = "請選擇需要匯入的檔案!";
                            ViewData["ErrorMsg"] = error;
                            //return View();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ViewData["ErrorMsg"] = ex.Message;
            } 
            //return Json(returnUserInfo);
            ViewData["returnUserInfo"] = returnUserInfo;
            return View();
        }