BootStrap Fileinput插件和Bootstrap table表格插件相结合(3)

//保存导入的数据 function SaveImport() { var list = [];//构造集合对象 var rows = $import.bootstrapTable('getSelections'); for (var i = 0; i < rows.length; i++) { list.push({ 'Name': rows[i].Name, 'Mobile': rows[i].Mobile, 'Email': rows[i].Email, 'Homepage': rows[i].Homepage, 'Hobby': rows[i].Hobby, 'Gender': rows[i].Gender, 'Age': rows[i].Age, 'BirthDate': rows[i].BirthDate, 'Height': rows[i].Height, 'Note': rows[i].Note }); } if (list.length == 0) { showToast("请选择一条记录", "warning"); return; } var postData = { 'list': list };//可以增加其他参数,如{ 'list': list, 'Rucanghao': $("#Rucanghao").val() }; postData = JSON.stringify(postData); $.ajax({ url: '/TestUser/SaveExcelData', type: 'post', dataType: 'json', contentType: 'application/json;charset=utf-8', traditional: true, success: function (data) { if (data.Success) { //保存成功 1.关闭弹出层,2.清空记录显示 3.刷新主列表 showToast("保存成功"); $("#import").modal("hide"); $(bodyTag).html(""); Refresh(); } else { showToast("保存失败:" + data.ErrorMessage, "error"); } }, data: postData }); }

3、后台控制器代码分析

这里我们的JS代码里面,涉及了几个MVC后台的方法处理:Upload、CheckExcelColumns、GetExcelData、SaveExcelData。这里分别进行介绍。

文件上传的后台控制器方法如下所示。      

/// <summary> /// 上传附件到服务器上 /// </summary> /// <param>附件信息</param> /// <param>附件组GUID</param> /// <param>指定的上传目录</param> /// <returns></returns> [AcceptVerbs(HttpVerbs.Post)] public ActionResult Upload(string guid, string folder) { CommonResult result = new CommonResult(); HttpFileCollectionBase files = HttpContext.Request.Files; if (files != null) { foreach (string key in files.Keys) { try { #region MyRegion HttpPostedFileBase fileData = files[key]; if (fileData != null) { HttpContext.Request.ContentEncoding = Encoding.GetEncoding("UTF-8"); HttpContext.Response.ContentEncoding = Encoding.GetEncoding("UTF-8"); HttpContext.Response.Charset = "UTF-8"; // 文件上传后的保存路径 string filePath = Server.MapPath("~/UploadFiles/"); DirectoryUtil.AssertDirExist(filePath); string fileName = Path.GetFileName(fileData.FileName); //原始文件名称 string fileExtension = Path.GetExtension(fileName); //文件扩展名 //string saveName = Guid.NewGuid().ToString() + fileExtension; //保存文件名称 FileUploadInfo info = new FileUploadInfo(); info.FileData = ReadFileBytes(fileData); if (info.FileData != null) { info.FileSize = info.FileData.Length; } info.Category = folder; info.FileName = fileName; info.FileExtend = fileExtension; info.AttachmentGUID = guid; info.AddTime = DateTime.Now; info.Editor = CurrentUser.Name;//登录人 result = BLLFactory<FileUpload>.Instance.Upload(info); if (!result.Success) { LogTextHelper.Error("上传文件失败:" + result.ErrorMessage); } } #endregion } catch (Exception ex) { result.ErrorMessage = ex.Message; LogTextHelper.Error(ex); } } } else { result.ErrorMessage = "fileData对象为空"; } return ToJsonContent(result); }

文件上传处理后,返回一个通用的CommonResult 的结果对象,也方便我们在JS客户端进行判断处理。

而其中检查我们导入Excel的数据是否满足列要求的处理,就是判断它的数据列和我们预先设置好的列名是否一致即可。    

//导入或导出的字段列表 string columnString = "姓名,手机,邮箱,主页,兴趣爱好,性别,年龄,出生日期,身高,备注"; /// <summary> /// 检查Excel文件的字段是否包含了必须的字段 /// </summary> /// <param>附件的GUID</param> /// <returns></returns> public ActionResult CheckExcelColumns(string guid) { CommonResult result = new CommonResult(); try { DataTable dt = ConvertExcelFileToTable(guid); if (dt != null) { //检查列表是否包含必须的字段 result.Success = DataTableHelper.ContainAllColumns(dt, columnString); } } catch (Exception ex) { LogTextHelper.Error(ex); result.ErrorMessage = ex.Message; } return ToJsonContent(result); }

而GetExcelData则是格式化Excel数据到具体的List<TestUserInfo>集合里面,这样我们方便在客户端进行各种属性的操作,它的代码如下所示。     

/// <summary> /// 获取服务器上的Excel文件,并把它转换为实体列表返回给客户端 /// </summary> /// <param>附件的GUID</param> /// <returns></returns> public ActionResult GetExcelData(string guid) { if (string.IsNullOrEmpty(guid)) { return null; } List<TestUserInfo> list = new List<TestUserInfo>(); DataTable table = ConvertExcelFileToTable(guid); if (table != null) { #region 数据转换 int i = 1; foreach (DataRow dr in table.Rows) { bool converted = false; DateTime dtDefault = Convert.ToDateTime("1900-01-01"); DateTime dt; TestUserInfo info = new TestUserInfo(); info.Name = dr["姓名"].ToString(); info.Mobile = dr["手机"].ToString(); info.Email = dr["邮箱"].ToString(); info.Homepage = dr["主页"].ToString(); info.Hobby = dr["兴趣爱好"].ToString(); info.Gender = dr["性别"].ToString(); info.Age = dr["年龄"].ToString().ToInt32(); converted = DateTime.TryParse(dr["出生日期"].ToString(), out dt); if (converted && dt > dtDefault) { info.BirthDate = dt; } info.Height = dr["身高"].ToString().ToDecimal(); info.Note = dr["备注"].ToString(); info.Creator = CurrentUser.ID.ToString(); info.CreateTime = DateTime.Now; info.Editor = CurrentUser.ID.ToString(); info.EditTime = DateTime.Now; list.Add(info); } #endregion } var result = new { total = list.Count, rows = list }; return ToJsonContent(result); }

另一个SaveExcelData的函数就是处理数据导入的最终处理函数,主要就是把集合写入到具体的数据库里面即可,具体代码如下所示。    

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wydswx.html