"" "" "" "This Code from Senior" "" "" "" "" 1: First need to add the import Excel and export Excel buttons in the front-end Display Interface view: @using (Html.BeginForm ()) { Note here that exporting Excel is the way to export data by getting the current form. 2: Then add an import method for importing Excel Function:js section with Picture 3: Add a Click event to pop up the interface (Importexcel-window): @using (Html.BeginForm ("Importexcel", "Family", FormMethod.Post, new {enctype = "multipart/form-data"}))//Here "Family" is the name of the controller {//"Importexcel" is the corresponding method name in the controller @Ht ml. AntiForgeryToken ()
} 4: Add import Excel and Export Excel method on controller side: [HttpPost] public ActionResult importexcel () {if (_workcontext.currentvendor! = null) return Accessdeniedview (); try {var file = request.files["Importexcelfile"]; if (file! = null && file. ContentLength > 0) {_importmanager.importfamiliesfromxlsx (file. InputStream); } else {errornotification (_localizationservice.getresource ("Admin.Common.UploadFile")); return Redirecttoaction (" Getfamilylistinfo "); } successnotification (_localizationservice.getresource ("Import Successful")); Return redirecttoaction ("Getfamilylistinfo"); } catch (Exception exc) {errornotification (exc); return redirecttoaction ("Getfamilylistinfo");}} This inside _importmanager.importfamiliesfromxlsx (file. InputStream) in _importmanager is to instantiate the interface and invoke the method in the interface importfamiliesfromxlsx () Add Member variable _importmanager:private readonly Iimportmanager _importmanager; Interface Iimportmanager:public Partial interface Iimportmanager {////Import products from XLSX file // stream void Importfamiliesfromxlsx (Stream stream); The implementation of the Iimportmanager interface method: Public partial class importmanager:iimportmanager{public void Importfamiliesfromxlsx (Stream s Tream) {using (var xlpackage = new Excelpackage (stream)) {//the workbook that gets the first table is var worksheet = XlPackage.Workbook.Worksheets.Fir Stordefault (); if (worksheet = = null) throw new Nopexception ("No worksheet found"); property of the column var properties = new[] {"Householder name",}; Insert password and account var directly to user table when importing data password = ""; var passwordsalt = ""; Switch (_customersettings.defaultpasswordformat) {case passwordformat.clear: {password = Phone,} break, Case PASSWORDFO Rmat. Encrypted: {password = _encryptionservice.encrypttext (Phone);} break; Case passwordformat.hashed: {string saltkey = _encryptionservice.createsaltkey (5); PasswordSalt = Saltkey; Password = _encryptionservice.createpasswordhash (Phone, Saltkey, _customersettings.hashedpasswordformat); } break; Default:break; } var customer = new Customer {Customerguid = Guid.NewGuid (), Email = Phone + "@GT. com", Username = phone, VendorID = 0, admincomment = "", Istaxexempt = False, Password = Password, PasswordSalt = PasswordSalt, Passwordformat = _customersettings.defaultpasswordformat, Active = true, CREATEDONUTC = Date Time.utcnow, LASTACTIVITYDATEUTC = Datetime.utcnow,}; _customerservice.insertcustomer (customer); Update role var allcustomerroles = _customerservice.getallcustomerroles (true); foreach (Var customerrole in allcustomerroles) {if (Customerrole.systemname = = systemcustomerrolenames.registered) {cus Tomer. Customerroles.add (Customerrole); }} _customerservice.updatecustomer (customer); Insert successful int iRow = 2;//row while (true) {bool Allcolumnsareempty = true; if (worksheet) to the user table. Cells[irow, 2]. Value! = NULL &&! String.IsNullOrEmpty (worksheet. Cells[irow, 2]. Value.tostring ())) {Allcolumnsareempty = false;} if (allcolumnsareempty) break; String Name = convertcolumntostring (worksheet. Cells[irow, Getcolumnindex (Properties, "name of the Householder")]. Value); Here is the main explanation for the corresponding property valuesIt is best to get the same order of the column's property values as above, save time for code review later, and set the string "Householder name" to be the same as the value of the Set column property as var group = _groupservice.getallgroups (). FirstOrDefault (m = M.name = = Groupexcel.trim () && m.village.name = = Villageexcel.trim ());// Here, if there is a relationship between the table and the table need to make a link query to obtain the foreign key value, otherwise no navigation will import failure, such as a village under a lot of groups, each group under a lot of family, here _groupservice.getallgroups () is the query. if (group = = null) {break;} var family = _familyservice.getallfamilies (). FirstOrDefault (f = f.idcardnumber = = Idcardnumber);//_family here. Getallfamilies () is to get the whole family. BOOL newfamily = false; if (family = = null) {family = new family (); newfamily = true;} family. name = name; Family. GroupId = group. id;//the ID value of the group here is the value of the foreign key we need if (newfamily) {_familyservice.insertfamily (family);} else {_familyservice.updatefamily ( Family); }//next product irow++; }}} to Excel:[httppost, ActionName ("Getfamilylistinfo")]//here the ActionName is a way to display a view of the list of information, It is also a way to import features and the view in which they are exported. [Formvaluerequired ("Exportexcel-all")]//This value is the value of the name of the "Export Excel" button returned by the front end public ActionResult Exportexcelall (FaMilymodel model) {if (!_permissionservice.authorize (standardpermissionprovider.managecustomers)) return Accessdeniedview (); var familys = _familyservice.getallfamilies ();//This is the information to get all the families try {byte[] bytes; using (var stream = new MemoryStream ()) { _exportmanager.exportfamiliestoxlsx (stream, familys); bytes = stream. ToArray (); } return File (bytes, "Text/xls", "familys.xlsx"); } catch (Exception exc) {errornotification (exc); return redirecttoaction ("Getfamilylistinfo");}} The same _exportmanager.exportfamiliestoxlsx (stream, Familys) is the interface that implements the export of Excel methods and calls the method Exportfamiliestoxlsx () to add member variables _ Exportmanager:private readonly Iexportmanager _exportmanager; Iexportmanager interface: Public partial interface iexportmanager{//// Export family list to XLSX //Stream///Customers void exportfamiliestoxlsx (Stream stream, IQueryable
C # operations Excel import Export while inserting account and password to user table