Recently began to learn MVC, without the previous powerful webform inside the control, feel a bit unaccustomed, slowly good.
The MVC import of Excel and WebForm is actually not much different, the following is the code:
Code for View stationimport.cshtml:
650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "/>
@{ viewbag.title = "Stationimport"; layout = "~/areas/admin/views/shared/_index.cshtml";} @using (Html.BeginForm ("Stationimport", "station", formmethod.post, new { enctype = "Multipart/form-data"  }) { 650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "/>
Code for controller-related methods: Use the TransactionScope class to ensure that all stored data is successfully executed before it is complete. If you want to use the TransactionScope class, you must add the System.Transaction component to your project.
650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "/>
#region Batch import of base stations 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) &NBSP;&NBSP;&NBsp; { ViewBag.error = "File cannot be empty"; return view (); } else { string filename= path.getfilename (file. FileName); int filesize = file. contentlength;//gets the size of the uploaded file in bytes Byte &nbsP; string fileex = system.io.path.getextension (filename);//Gets the extension of the uploaded file string nofilename = system.io.path.getfilenamewithoutextension (filename);//Get file name with no extension int maxsize = 4000 * 1024 ;//define the maximum size of the uploaded file as 4m string filetype = ". Xls,.xlsx";//define the type string of the uploaded file filename = nofilename + datetime.now.tostring (" Yyyymmddhhmmss ") + fileEx; if (! Filetype.contains (Fileex)) &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp; { ViewBag.error = "file type is not correct, import only files in XLS and xlsx formats"; return view (); } if ( Filesize >= maxsize) { ViewBag.error = "Upload file more than 4M, cannot upload"; 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&NBSP;EX) { viewbag.error = ex. Message; return view (); } datatable table = mydataset.tables["ExcelInfo"] . Defaultview.totable (); //referencing transaction mechanism, when error occurs, things roll back using (transactionscope transaction = new TransactionScope ()) { for (int i = 0; i < table. rows.count; i++) { //Get region name string _areaname = table. Rows[i][0]. ToString (); //determine whether the region exists if (!_arearepository.checkareaexist (_areaname)) { ViewBag.error = "Imported Files:" + _areaName + "area does not exist, please add the region first"; 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 (); &nBsp; station. Oilenginecapacity = decimal. Parse (table. ROWS[I][4]. ToString ()); _stationrepository.addstation (station); } } transaction. Complete (); } ViewBag.error = "Import Successful"; system.threading.thread.sleep (; ) return redirecttoactIon ("Index"); } #endregion
650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "/>
File download, the Fileresult class can respond to arbitrary file content, including binary format data, the implementation of the Fileresult class subclass in ASP. 3 in total, respectively
1. Filepathresult: Responding to an entity file
2. Filecontentresult: Responds to the contents of a byte array
3, Filestreamresult: response to a stream data
What is the difference between Filepathresult and Filestreamresult? What are we to choose? The main difference is that Filepathresult uses Httpresponse.transmitfile to write files to the HTTP output stream. This method does not buffer in server memory, so this is a good choice for sending large files. Their differences are much like the difference between DataReader and datasets. At the same time, TransmitFile also has a bug, which may cause the file to be sent to the client half stopped, or even unable to transfer. And Filestreamresult is great in this respect. For example: Returns the chart picture that the ASP. NET chart control generates in memory, which does not require that the picture be saved to disk.
The File () helper method can be automatically selected for different Fileresult classes.
The following is the code for the file download:
Public Fileresult GetFile () {String path = AppDomain.CurrentDomain.BaseDirectory + "uploads/excel/"; String fileName = "Base station information Excel template. xls"; return File (path + filename, "Text/plain", fileName); }
This article is from the "Shadow of War" blog, be sure to keep this source http://rmlifejun.blog.51cto.com/7683304/1621485
ASP. NET MVC Excel Import