首页 > 代码库 > c#操作excel导入导出时同时向用户表插入账户与密码

c#操作excel导入导出时同时向用户表插入账户与密码

《》《》《》《》本代码源于师兄《》《》《》《》《》《》 1:首先需要在前端显示界面View视图中添加导入Excel和导出Excel按钮: @using (Html.BeginForm()) {
} 这里注意,导出Excel是通过获取当下的表单的方式来导出数据的。 2:然后为导入Excel添加导入方法function:    js部分以图片存放 3:添加点击事件后弹出来的操作界面(importexcel-window):
@using (Html.BeginForm("ImportExcel", "Family", FormMethod.Post, new { enctype = "multipart/form-data" })) //这里"Family"是控制器的名称 { //"ImportExcel"是控制器中相应方法名称 @Html.AntiForgeryToken()
@T("Excel文件"):
}
4:在控制器端添加导入Excel和导出Excel方法: [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("导入成功")); return RedirectToAction("GetFamilyListInfo"); } catch (Exception exc) { ErrorNotification(exc); return RedirectToAction("GetFamilyListInfo"); } } 这里面 _importManager.ImportFamiliesFromXlsx(file.InputStream) 中_importManager是实例化接口并调用接口中的方法ImportFamiliesFromXlsx() 添加成员变量_importManager:private readonly IImportManager _importManager; 接口IImportManager : public partial interface IImportManager { /// /// Import products from XLSX file /// /// Stream void ImportFamiliesFromXlsx(Stream stream); } IImportManager接口方法的实现: public partial class ImportManager : IImportManager { public void ImportFamiliesFromXlsx(Stream stream) { using (var xlPackage = new ExcelPackage(stream)) { //得到第一个表的工作簿 var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault(); if (worksheet == null) throw new NopException("No worksheet found");          //列的属性 var properties = new[] { "户主姓名", };     //导入数据时直接向用户表插入密码和账户 var password = ""; var PasswordSalt = ""; switch (_customerSettings.DefaultPasswordFormat) { case PasswordFormat.Clear: { password = Phone; } break; case PasswordFormat.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 = DateTime.UtcNow, LastActivityDateUtc = DateTime.UtcNow, }; _customerService.InsertCustomer(customer); //更新角色 var allCustomerRoles = _customerService.GetAllCustomerRoles(true); foreach (var customerRole in allCustomerRoles) { if (customerRole.SystemName == SystemCustomerRoleNames.Registered) { customer.CustomerRoles.Add(customerRole); } } _customerService.UpdateCustomer(customer); //向用户表插入成功 int iRow = 2;//行 while (true) { bool allColumnsAreEmpty = true; if (worksheet.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, "户主姓名")].Value); //这里主要说明一下在进行相应属性值获取的时候最好跟上面设置列的属性值的顺序一样,为后面进行代码审查的时候节省时间,同时这里面设置的字符串"户主姓名"要与设置列属性的值一样 var group = _groupService.GetAllGroups().FirstOrDefault(m => m.Name == groupExcel.Trim() && m.Village.Name == villageExcel.Trim());//这里如果有表跟表之间的关系的时候需要进行链接查询来获得外键值,否则没有导航就会导入失败,就比如一个村子下面有很多个组,每个组下面又有很多的家庭,这里的_groupService.GetAllGroups()就是进行查询. if (group == null) { break; } var family = _familyService.GetAllFamilies().FirstOrDefault(f => f.IDcardnumber == IDcardnumber);//这里的_family.GetAllFamilies()是得到全部的家庭. bool newFamily = false; if (family == null) { family = new Family(); newFamily = true; } family.Name = Name; family.GroupId = group.Id;//这里组的id值就是我们所需要的外键的值 if (newFamily) { _familyService.InsertFamily(family); } else { _familyService.UpdateFamily(family); } //next product iRow++; } } } } 导出到excel: [HttpPost, ActionName("GetFamilyListInfo")]//这里注意这里的ActionName是显示信息列表对应的视图的方法,同时也是导入功能和导出功能所在的视图的方法. [FormValueRequired("exportexcel-all")]//这里面的值就是前端传回来的"导出Excel"按钮的name的值 public ActionResult ExportExcelAll(FamilyModel model) { if (!_permissionService.Authorize(StandardPermissionProvider.ManageCustomers)) return AccessDeniedView(); var familys = _familyService.GetAllFamilies();//这里是得到全部家庭的信息 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"); } } 同样的这里面的_exportManager.ExportFamiliesToXlsx(stream, familys)是实现导出Excel方法的接口并调用方法ExportFamiliesToXlsx() 添加成员变量_exportManager:private readonly IExportManager _exportManager; IExportManager 接口: public partial interface IExportManager { /// /// Export family list to XLSX /// /// Stream /// Customers void ExportFamiliesToXlsx(Stream stream, IQueryable

c#操作excel导入导出时同时向用户表插入账户与密码