博 之 文

以 拼 搏 设 计 梦 想 , 以 恒 心 编 程 明 天
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

MVC4上传Excel到数据库

Posted on 2014-02-27 18:38  IsNull_Soft  阅读(240)  评论(0)    收藏  举报
@{
    ViewBag.Title = "SampleInputIndex";
}
<h2>SampleInputIndex</h2>
<div id="main-content">
    <div id="main-content">
        <div class="content-box">
            <div class="content-box-content">
                @using (Html.BeginForm("SampleInputIndex", "SampleInput", FormMethod.Post, new { enctype = "multipart/form-data" }))
                {
                    <form>
                        @Html.Label("Id", "请选择上传文件") <input id="fileExcel" type="file" name="FileUpload1" />
                        <input type="submit" name="Submit" id="Submit" value="确定" />
                    </form>
                }
                @using (Html.BeginForm("ImpReporInput", "SampleInput", FormMethod.Post, new { enctype = "multipart/form-data" }))
                {
                    <form>
                        @Html.Label("Id", "请选择上传文件1") <input id="fileExcel" type="file" name="FileUpload1" />
                        <input type="submit" name="Submit" id="Submit" value="确定" />
                    </form>
                }
            </div>
        </div>
    </div>
</div>



         [HttpPost]
        public ActionResult SampleInputIndex(FormCollection collection)
        {
            Overlander.WebSite.Proxy.MemberServiceRef.VizzExecResponse response = new Proxy.MemberServiceRef.VizzExecResponse();
            string path = String.Empty;
            bool bl = Upload(collection, out path);
            if (bl == false)
            {
                return View();
            }
            string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1'";
            using (OleDbConnection odbcConn = new OleDbConnection(strConn))
            {
                odbcConn.Open();
                DataTable dt = odbcConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                
                using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.AppSettings["conn"]))
                {
                    try
                    {
                        sqlConn.Open();
                        SqlCommand cmd = new SqlCommand();
                        cmd.Connection = sqlConn;
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = "DELETE FROM dbo.ImpMember";

                        cmd.ExecuteNonQuery();


                        cmd.CommandText = "INSERT INTO [dbo].[ImpMember]" +
                                               "([Member No],[Family Name],[Given Name])"
                                            "VALUES" +
                                                "(@MemberNo,@FamilyName,@GivenName)"

                        cmd.Parameters.Add("@MemberNo", SqlDbType.NVarChar);
                        cmd.Parameters.Add("@FamilyName", SqlDbType.NVarChar);
                        cmd.Parameters.Add("@GivenName", SqlDbType.NVarChar);
                        if (dt.Rows.Count > 0)
                        {
                            foreach (DataRow row in dt.Rows)
                            {
                                OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [" + row["TABLE_NAME"] + "]", odbcConn);
                                DataSet ds = new DataSet();
                                adapter.Fill(ds);
                                foreach (DataRow datarow in ds.Tables[0].Rows)
                                {
                                    cmd.Parameters["@MemberNo"].Value = datarow[0].ToString();
                                    cmd.Parameters["@FamilyName"].Value = datarow[1].ToString();
                                    cmd.Parameters["@GivenName"].Value = datarow[2].ToString();
                                    
                                    cmd.ExecuteNonQuery();
                                }
                            }
                        }
                    }
                    finally
                    {
                        try
                        {
                            Overlander.WebSite.Proxy.MemberServiceRef.VizzExecRequest request = new Proxy.MemberServiceRef.VizzExecRequest();
                            Overlander.WebSite.Proxy.Services.MemberProxy client = new Proxy.Services.MemberProxy();
                            response = client.MemberDataImport(request);
                        }
                        finally { }
                    }
                }
            }
            return View(response);
        }





         public Boolean Upload(FormCollection collection,out string path)
         {
             var c = Request.Files[0];
             path = String.Empty;
             if (c.ContentLength == 0) { return false; }
             if (c.FileName != "")
             {

                 string tempPath = "~/TempExcel/" + DateTime.Now.Year;
                 if (!Directory.Exists(Server.MapPath(tempPath)))
                 {
                     System.IO.Directory.CreateDirectory(Server.MapPath(tempPath));
                 }
                 tempPath = tempPath + "/" + DateTime.Now.Month;
                 if (!Directory.Exists(Server.MapPath(tempPath)))
                 {
                     System.IO.Directory.CreateDirectory(Server.MapPath(tempPath));
                 }

                 string extension = c.FileName.Substring(c.FileName.LastIndexOf('.'));//扩展名
                 string filename = c.FileName.Substring(0, (c.FileName.LastIndexOf('.')));//文件名
                 string ResulFileName = c.FileName.Replace(c.FileName, (filename + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + extension));
                 string[] str = { ".xls", ".xlsx" };
                 for (int i = 0; i < str.Length; i++)
                 {
                     if (!str.Contains(extension))
                     {
                         return false;
                     }
                 }

                 path = Server.MapPath((tempPath)) + "/" + ResulFileName;
                 if (System.IO.File.Exists(path))
                 {
                     System.IO.File.Delete(path);
                 }
                 c.SaveAs(path);
             }
             return true;
         }