天天看點

ASP.NET MVC excel導入

近來開始學習MVC,沒有了以前強大的webform裡面的控件,感覺有點不習慣,慢慢的就好了。

MVC導入excel和webform其實沒多大差別,以下為代碼:

視圖StationImport.cshtml的代碼:

ASP.NET MVC excel導入

@{
    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="width: 250px; height: 24px;
                    background: White" class="easyui-validatebox" /></p>
            <p>
                <input id="btnImport" type="submit" value="導入" style="width: 60px; height: 28px;" /></p>
            <p style="color: Red; text-align: center;">@ViewBag.error</p>
        </fieldset>
    </div>}      
ASP.NET MVC excel導入

控制器相關方法的代碼:使用TransactionScope類以确儲存儲資料全部都成功執行才算完成。如果要使用TransactionScope類,必須在項目中添加System.Transaction元件。

ASP.NET MVC excel導入
  #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      
ASP.NET MVC excel導入

檔案下載下傳,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);
        }      

繼續閱讀