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

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;
            }
           
        }
    }

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值