ASP.NET MVC3.0 上傳檔案並匯入

來源:互聯網
上載者:User

View

@model BSServer.Models.PagerIndexModel
@{
    ViewBag.Title = "網站資訊一覽";
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>網站資訊一覽</title>
    <link href="@Url.Content("~/Content/style/TableCss.css")" rel="stylesheet" type="text/css"/>
</head>
<body>
    <fieldset style="border-color: #B1CDE3">
        <p>
            @Html.ActionLink("新增網站  ", "AddSiteInfo", "SiteManage")
            @Html.ActionLink("匯出網站資訊  ", "ExportSiteInfo", "SiteManage", new { style = "Color: #46A3FF;" })
        </p>
        <p>
            @if (ViewBag.Flag == 1)
            {
                <script type="text/javascript">alert('匯入成功!')</script>
            }
            @using (Html.BeginForm("ImportSiteInfo", "SiteManage", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
                @Html.Label("匯入網站")<input id="fileSite" name="fileSite" type="file" title="匯入網站資訊" style="color: #46A3FF;" />
                <input type="submit" value="匯入" style="background-color: #B1CDE3" />
            }
        </p>
        <p>
            @using (Html.BeginForm("SiteInfoList", "SiteManage"))
            {
                <label id="localName">
                    地區名稱</label><input id="txtLocalName" name="txtLocalName" value="@ViewBag.LocalName" type="text" maxlength='20'/>
                <label id="locName">
                    網站名稱</label><input id="txtSiteName" name="txtSiteName"  value="@ViewBag.SiteName" type="text"  maxlength='20'/>
                <input type="submit" value="查詢" style="background-color: #B1CDE3" />
            }
        </p>
        <table width="100%">
            <tr>
                <td style="background-color: #B1CDE3">
                    網站ID
                </td>
                <td style="background-color: #B1CDE3">
                    地區
                </td>
                <td style="background-color: #B1CDE3">
                    網站名稱
                </td>
                <td style="background-color: #B1CDE3">
                    操作
                </td>
            </tr>
            @foreach (var site in Model.SiteInfomationList)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => site.ID)
                    </td>
                    <td>
                        @if (site.LocalID != -1)
                        {
                            @:@(BSServer.Business.BasicInfo.SiteManageBusiness.GetLocalNameByLocalId(site.LocalID))
                        }
                        else
                        {
                            @:@(string.Empty)
                                                 }
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => site.Name)
                    </td>
                    <td>
                        @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('是否要刪除?');" })
                    </td>
                </tr>
            }
            <tr>
                <td colspan='4' align='right'>
                    @Html.Partial("_Page", Model)
                </td>
            </tr>
        </table>
    </fieldset>
</body>
</html>
Controller

    /// <summary>
    /// 網站控制器
    /// </summary>
    public  class SiteManageController : Controller
    {       

        /// <summary>
        /// 匯入Excel方法
        /// </summary>
        /// <param name="fileSite"></param>
        /// <returns></returns>
        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
    {
        /// <summary>
        /// 擷取Excel資料方法
        /// </summary>
        /// <param name="filepath">檔案路徑</param>
        /// <param name="sheetname">sheet名稱</param>
        /// <returns></returns>
        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;
            }
           
        }
    }

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.