1. cshtml page Form
<form id= "form" method="post" action="/ Savevaluebatch" enctype=" Multipart/form-data "><input type=" File" name="uploadexcel" style="width:200px; " /></form>
2. Controller
[HttpPost] Publicactionresult savevaluebatch (iformcollection form) {Try { varFiles =request.form.files.where (x = X.name.equals ("Uploadexcel")); //non-null limit if(Files = =NULL|| Files. Count () <=0) {returnJson (New{issuccess =false, message ="Please select an Excel file to upload"},"text/html"); } //Formatting Restrictions varAllowtype =New string[] {"Application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}; if(Files. Any (b =!)allowtype.contains (B.contenttype))) { returnJson (New{issuccess =false, message ="only Excel 2007 format files can be uploaded"},"text/html"); } //Size Limit if(Files. Sum (b = b.length) >=1024x768*1024x768*4) { returnJson (New{issuccess =false, message ="The total size of the uploaded file can only be below 4M"},"text/html"); } //write to Server disk foreach(varFileinchfiles) { varFileName =file. FileName; varPath = Path.Combine (_host. Contentrootpath+"/upload", FileName); using(varstream =System.IO.File.Create (path)) {file. CopyTo (stream); } } returnJson (New{issuccess =true, message ="saved successfully"},"text/html"); } Catch(Exception e) {returnJson (New{issuccess =false, message ="Save failed:"+ E.innerexception.message},"text/html"); } }
Private ihostingenvironment _host; Public Excelcontroller (ihostingenvironment host) { = host; }
NET core upload and use Epplus to import Excel files