The MVC import of Excel and WebForm is actually not much different, the following is the code:
Code for View 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&G T Base station information Import 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.
#region Bulk import of the base station public ActionResult Stationimport () {return View (); } [HttpPost] public actionresult stationimport (HttpPostedFileBase filebase) {HTTPPOSTEDFI Lebase file=request.files["Files"; String FileName; String Savepath; if (file = = null| | File. contentlength<=0) {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 of byte 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;//defines the maximum space size for an uploaded file is 4M string FileType = ". Xls,.xlsx";//defines the type string for the uploaded file filename = nofile Name + DateTime.Now.ToSTring ("Yyyymmddhhmmss") + Fileex; if (! Filetype.contains (Fileex)) {viewbag.error = "file type is not correct, only import XLS and xlsx format files"; 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 ex) {viewbag.error = ex. Message; return View (); } DataTable table = mydataset.tables["Excelinfo"]. Defaultview.totable (); Reference transaction mechanism, when an error occurs, the thing rolls back using (TransactionScope transaction = new TransactionScope ()) {for (int i = 0; i < table.) Rows.Count; i++) {//Gets the region name string _areaname = table. Rows[i][0]. ToString (); Determine if the region exists if (!_arearepository.checkareaexist (_areaname)) { Viewbag.error = "Imported file:" + _areaname + "region 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 (); Station. oilenginecapacity = Decimal. Parse (table. ROWS[I][4]. ToString ()); _stationrepository.addstation (station); }} transaction.complete (); } viewbag.error = "Import succeeded"; System.Threading.Thread.Sleep (2000); Return redirecttoaction ("Index"); } #endregionFile 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); }
ASP. NET MVC imports Excel into the database