ASP.NET MVC3.0 上传文件并导入

View

@model BSServer.Models.PagerIndexModel
@{
    ViewBag.Title = "站点信息一览";
}


    站点信息一览
   


   


       


            @Html.ActionLink("新增站点  ", "AddSiteInfo", "SiteManage")
            @Html.ActionLink("导出站点信息  ", "ExportSiteInfo", "SiteManage", new { style = "Color: #46A3FF;" })
       


       


            @if (ViewBag.Flag == 1)
            {
               
            }
            @using (Html.BeginForm("ImportSiteInfo", "SiteManage", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
                @Html.Label("导入站点")
               
            }
       


       


            @using (Html.BeginForm("SiteInfoList", "SiteManage"))
            {
               
               
               
            }
       


       
           
               
               
               
               
           
            @foreach (var site in Model.SiteInfomationList)
            {
               
                   
                   
                   
                   
               
            }
           
               
           
       

                    站点ID
               

                    区域
               

                    站点名称
               

                    操作
               

                        @Html.DisplayFor(modelItem => site.ID)
                   

                        @if (site.LocalID != -1)
                        {
                            @:@(BSServer.Business.BasicInfo.SiteManageBusiness.GetLocalNameByLocalId(site.LocalID))
                        }
                        else
                        {
                            @:@(string.Empty)
                                                 }
                   

                        @Html.DisplayFor(modelItem => site.Name)
                   

                        @Html.ActionLink("查看", "SiteInfoDetails", new { id = site.ID }) |
                        @Html.ActionLink("编辑", "EditeSiteInfo", new { id = site.ID }) |
                        @Html.ActionLink("删除", "DeleteSite", new { siteId = site.ID }, new { onclick = "return confirm('是否要删除?');" })
                   

                    @Html.Partial("_Page", Model)
               

   



Controller

    ///


    /// 站点控制器
    ///

    public  class SiteManageController : Controller
    {       

        ///


        /// 导入Excel方法
        ///

        ///
        ///
        public ActionResult ImportSiteInfo()
        {
            try
            {
                #region 文件上传

                //文件路径
                string path = string.Empty;
                //文件名称
                string filename=string.Empty;
                //文件与路径
                string filePath = string.Empty;
                foreach (string upload in Request.Files)
                {
                    //判断当前上传控件是否为空
                    if (Request.Files.Count > 0)
                    {
                        //判断当前上传控件是否为空
                        if (Request.Files[upload] != null && Request.Files[upload].ContentLength > 0)
                            //当前工程路径与上传文件夹
                            path = AppDomain.CurrentDomain.BaseDirectory + "uploadSite/";
                        //文件名称
                        filename = Path.GetFileName(Request.Files[upload].FileName);
                        //文件与路径
                        filePath = Path.Combine(path, filename);
                        //保存在当前工程文件夹
                        Request.Files[upload].SaveAs(filePath);
                    }
                }
               
                #endregion

                #region 导入文件


                //判断是否为空导入
                if (string.IsNullOrEmpty(path))
                {
                    return RedirectToAction("SiteInfoList", "SiteManage");
                }
                else
                {
                    //判断当前文件是否为Excel
                    if (!filename.Contains("xls"))
                        return RedirectToAction("SiteInfoList", "SiteManage");
                }
                ImportExcel importEx = new ImportExcel();
                //获取Excel中的数据
                DataTable dtSite = importEx.ExcelDataSource(filePath, "Sheet1").Tables[0];
                //添加到数据库
                foreach (DataRow item in dtSite.Rows)
                {
                    Site s = new Site()
                    {
                        Name = item["Name"].ToString().Trim(),
                        LocalID = int.Parse(item["LocalID"].ToString().Trim())
                    };
                    //判断当前站点是否存在
                    if (!string.IsNullOrEmpty(SiteManageBusiness.GetSiteNameByName(s.Name)))
                        continue;
                    SiteManageBusiness.AddSiteInfo(s);
                }

                #endregion

                return RedirectToAction("SiteInfoList", "SiteManage", new { import = 1 });
            }
            catch (Exception ex)
            {
                return RedirectToAction("SystemError", "SysException", new { ExInfo = "堆栈消息:" + ex.StackTrace + "\n\n 异常消息:" + ex.Message });
            }
        }
    }

Common

 public class ImportExcel
    {
        ///


        /// 获取Excel数据方法
        ///

        /// 文件路径
        /// sheet名称
        ///
        public DataSet ExcelDataSource(string filepath, string sheetname)
        {
            try
            {
                string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;";
                OleDbConnection conn = new OleDbConnection(strConn);
                OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + sheetname + "$]", strConn);
                DataSet ds = new DataSet();
                oada.Fill(ds);
                return ds;
            }
            catch (Exception ex)
            {

                throw ex;
            }
           
        }
    }

 

 

 

你可能感兴趣的:(开发应用)