zoukankan      html  css  js  c++  java
  • ASP.NET MVC导入excel到数据库

    MVC导入excel和webform其实没多大区别,以下为代码:

    视图StationImport.cshtml的代码:

    复制代码
    @{
        ViewBag.Title = "StationImport";
        Layout = "~/Areas/Admin/Views/Shared/_index.cshtml";
    }
    @using (Html.BeginForm("StationImport", "Station", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <h2>
            基站信息导入</h2>
        <div>
            <fieldset id="myfieldset">
                <legend>excel模版格式 </legend><font color="red">导入基站的模板格式如下,若模板格式不正确,则相应的基站不能导入!</font><br />
                <img src="http://www.cnblogs.com/http://www.cnblogs.com/Content/AdminImages/stationexceltemplate.png" />
                <p style="color: Red; text-align: center;">@Html.ActionLink("下载模版", "GetFile")</p>
            </fieldset>
        </div>
        <div style="margin-top: 20px;">
            <fieldset id="myfieldset1">
                <legend>基站批量信息导入</legend>
                <p>
                    选择文件:<input id="FileUpload" type="file" name="files" style=" 250px; height: 24px;
                        background: White" class="easyui-validatebox" /></p>
                <p>
                    <input id="btnImport" type="submit" value="导入" style=" 60px; height: 28px;" /></p>
                <p style="color: Red; text-align: center;">@ViewBag.error</p>
            </fieldset>
        </div>
    }
    复制代码

    控制器相关方法的代码:使用TransactionScope类以确保存储数据全部都成功执行才算完成。如果要使用TransactionScope类,必须在项目中添加System.Transaction组件。

    复制代码
      #region 批量导入基站
            public ActionResult StationImport()
            {
                return View();
            }
            [HttpPost]
            public ActionResult StationImport(HttpPostedFileBase filebase)
            {
                HttpPostedFileBase file=Request.Files["files"];
                string FileName;
                string savePath;
                if (file == null||file.ContentLength<=0)
                {
                    ViewBag.error = "文件不能为空";
                    return View();
                }          
                else
                {    
                   string filename= Path.GetFileName(file.FileName);  
                   int filesize = file.ContentLength;//获取上传文件的大小单位为字节byte
                   string fileEx = System.IO.Path.GetExtension(filename);//获取上传文件的扩展名
                   string NoFileName = System.IO.Path.GetFileNameWithoutExtension(filename);//获取无扩展名的文件名
                   int Maxsize = 4000 * 1024;//定义上传文件的最大空间大小为4M
                   string FileType = ".xls,.xlsx";//定义上传文件的类型字符串
    
                   FileName = NoFileName + DateTime.Now.ToString("yyyyMMddhhmmss") + fileEx;
                    if (!FileType.Contains(fileEx))
                    {
                        ViewBag.error = "文件类型不对,只能导入xls和xlsx格式的文件";
                        return View();
                    }
                    if (filesize >= Maxsize)
                    {
                        ViewBag.error = "上传文件超过4M,不能上传";
                        return View();
                    }
                    string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/excel/";
                     savePath = Path.Combine(path, FileName);
                    file.SaveAs(savePath);
                }
                
                //string result = string.Empty;
                string strConn;
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +savePath+ ";" + "Extended Properties=Excel 8.0";
                OleDbConnection conn = new OleDbConnection(strConn);
                conn.Open();
                OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$]", strConn);
                DataSet myDataSet = new DataSet();
                try
                {
                    myCommand.Fill(myDataSet, "ExcelInfo");
                }
                catch (Exception ex)
                {
                    ViewBag.error = ex.Message;
                    return View();
                }
                DataTable table = myDataSet.Tables["ExcelInfo"].DefaultView.ToTable();
                
                //引用事务机制,出错时,事物回滚
                using (TransactionScope transaction = new TransactionScope())
                {
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        //获取地区名称
                        string _areaName = table.Rows[i][0].ToString();
                        //判断地区是否存在
                        if (!_areaRepository.CheckAreaExist(_areaName))
                        {
                            ViewBag.error = "导入的文件中:" + _areaName + "地区不存在,请先添加该地区";
                            return View();
                        }
                        else
                        {
                            Station station = new Station();
                            station.AreaID = _areaRepository.GetIdByAreaName(_areaName).AreaID;
                            station.StationName = table.Rows[i][1].ToString();
                            station.TerminaAddress = table.Rows[i][2].ToString();
                            station.CapacityGrade = table.Rows[i][3].ToString();
                            station.OilEngineCapacity = decimal.Parse(table.Rows[i][4].ToString());
                            _stationRepository.AddStation(station);
                        }
                    }
                    transaction.Complete();
                }
                ViewBag.error = "导入成功";
                System.Threading.Thread.Sleep(2000);
                return RedirectToAction("Index");
            }
            #endregion
    复制代码

    文件下载,FileResult类可以响应任意的文件内容,包括二进制格式的数据,在ASP.NET MVC中实现FileResult类的子类共有3个,分别是

    1、FilePathResult:响应一个实体文件

    2、FileContentResult:响应一个byte数组的内容

    3、FileStreamResult:响应一个Stream数据

    FilePathResult和FileStreamResult的区别是什么?我们又该如何取舍呢?主要的区别是FilePathResult使用HttpResponse.TransmitFile来将文件写入Http输出流。这个方法并不会在服务器内存中进行缓冲,所以这对于发送大文件是一个不错的选择。他们的区别很像DataReader和DataSet的区别。于此同时, TransmitFile还有一个bug,这可能导致文件传到客户端一半就停了,甚至无法传送。而FileStreamResult在这方面就很棒了。比如说:返回Asp.net Chart 控件在内存中生成的图表图片,而这并不需要将图片存到磁盘中.

    File()辅助方法能自动选取不同的FileResult类进行。

    以下为文件下载的代码:

          public FileResult GetFile()
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/excel/";
                string fileName = "基站信息Excel模版.xls";
                return File(path + fileName, "text/plain", fileName);
            }
  • 相关阅读:
    (9)ASP.NET Core2.2 中的MVC路由二
    (8)ASP.NET Core2.2 中的MVC路由一
    (7)ASP.NET Core2.2 中的错误处理
    (6)ASP.NET Core2.2 中使用IHttpClientFactory发出HTTP请求
    (5)ASP.NET Core2.2 中的静态文件
    (4)ASP.NET Core2.2 中间件
    蒲公英 &#183; JELLY技术周刊 Vol.05: Rust & Electron 的高性能实践 -- Finda
    Taro 2.2 全面插件化,支持拓展和定制个性化功能
    使用 Taro 快速开发京东小程序
    技术周刊 · 0202 年了,你还不学一下 WASM 么?
  • 原文地址:https://www.cnblogs.com/lishuyi/p/4578718.html
Copyright © 2011-2022 走看看