近來開始學習MVC,沒有了以前強大的webform里面的控件,感覺有點不習慣,慢慢的就好了。
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="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> }
控制器相關方法的代碼:使用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); }