Home > Web Front-end > JS Tutorial > body text

The BootStrap Fileinput plug-in and the table plug-in are combined to realize the steps of file upload, preview and submission of imported Excel data.

巴扎黑
Release: 2018-05-15 10:53:25
Original
5106 people have browsed it

This article mainly introduces the steps of importing Excel data by combining the BootStrap Fileinput plug-in and the Bootstrap table table plug-in to realize file upload, preview, and submission. Friends in need can refer to the

bootstrap-fileinput source code: https://github.com/kartik-v/bootstrap-fileinput

bootstrap-fileinput Online API: http://plugins.krajee.com/file-input

bootstrap-fileinput Demo Display: http://plugins.krajee.com/file-basic-usage-demo

This plug-in mainly introduces how to handle image upload processing operations. Originally, my Excel import operation used the Uploadify plug-in. You can refer to my essay "Usage of Attachment Upload Component Uploadify", but this requires Flash control support, which is more troublesome in some browsers (such as Chrome), so I decided to use a more general upload plug-in. This time, first of all, based on The framework system of the Bootstrap front-end architecture has been upgraded to replace the original Uploadify plug-in, so that the page upload function can be implemented without any difference in various browsers.

Generally, we need to introduce the following two files before the plug-in can be used normally:

bootstrap-fileinput/css/fileinput.min.css
bootstrap-fileinput/js/fileinput.min.js
Copy after login

When using the File input plug-in, if it is based on Asp.NET MVC, then we can Use BundleConfig.cs to add the corresponding reference and add it to the Bundles collection reference.

 //添加对bootstrap-fileinput控件的支持
 css_metronic.Include("~/Content/MyPlugins/bootstrap-fileinput/css/fileinput.min.css");
 js_metronic.Include("~/Content/MyPlugins/bootstrap-fileinput/js/fileinput.min.js");
 js_metronic.Include("~/Content/MyPlugins/bootstrap-fileinput/js/locales/zh.js");
Copy after login

In the page, we use the following HTML code to implement the interface display. The main bootstrap fileinput plug-in statement is mainly the basic interface code.

<input id="excelFile" type="file">
Copy after login

The interface display imported from Excel is as follows.

After selecting the specified file, we can see the Excel file list, as shown in the following interface.

After uploading the file, the data is directly displayed in the list of the pop-up layer. The Bootstrap-table table plug-in is used directly for display.

In this way, we can display the Excel records, realize the preview function, check the necessary records, and then save them and submit them to the server for saving. This is achieved Real import of Excel data into database for processing.

2. Detailed introduction to Excel export operation

In the interface where we actually import Excel, the HTML code is as follows.



 

测试用户信息-模板 TestUser-模板.xls


<input id="excelFile" type="file">

Copy after login

For various attributes of bootstrap fileinput, we use JS to initialize them here, which facilitates unified management and modification.

 //初始化Excel导入的文件
 function InitExcelFile() {
 //记录GUID
 $("#AttachGUID").val(newGuid());
 $("#excelFile").fileinput({
 uploadUrl: "/FileUpload/Upload",//上传的地址
 uploadAsync: true, //异步上传
 language: "zh",  //设置语言
 showCaption: true, //是否显示标题
 showUpload: true, //是否显示上传按钮
 showRemove: true, //是否显示移除按钮
 showPreview : true, //是否显示预览按钮
 browseClass: "btn btn-primary", //按钮样式 
 dropZoneEnabled: false, //是否显示拖拽区域
 allowedFileExtensions: ["xls", "xlsx"], //接收的文件后缀
 maxFileCount: 1,  //最大上传文件数限制
 previewFileIcon: &#39;<i class="glyphicon glyphicon-file"></i>&#39;,
 allowedPreviewTypes: null,
 previewFileIconSettings: {
  &#39;docx&#39;: &#39;<i class="glyphicon glyphicon-file"></i>&#39;,
  &#39;xlsx&#39;: &#39;<i class="glyphicon glyphicon-file"></i>&#39;,
  &#39;pptx&#39;: &#39;<i class="glyphicon glyphicon-file"></i>&#39;,
  &#39;jpg&#39;: &#39;<i class="glyphicon glyphicon-picture"></i>&#39;,
  &#39;pdf&#39;: &#39;<i class="glyphicon glyphicon-file"></i>&#39;,
  &#39;zip&#39;: &#39;<i class="glyphicon glyphicon-file"></i>&#39;,
 },
 uploadExtraData: { //上传的时候,增加的附加参数
  folder: &#39;数据导入文件&#39;, guid: $("#AttachGUID").val()
 }
 }) //文件上传完成后的事件
 .on(&#39;fileuploaded&#39;, function (event, data, previewId, index) {
 var form = data.form, files = data.files, extra = data.extra,
  response = data.response, reader = data.reader;
 var res = data.response; //返回结果
 if (res.Success) {
  showTips(&#39;上传成功&#39;);
  var guid = $("#AttachGUID").val();
  //提示用户Excel格式是否正常,如果正常加载数据
  $.ajax({
  url: &#39;/TestUser/CheckExcelColumns?guid=&#39; + guid,
  type: &#39;get&#39;,
  dataType: &#39;json&#39;,
  success: function (data) {
  if (data.Success) {
  InitImport(guid); //重新刷新表格数据
  showToast("文件已上传,数据加载完毕!");
  //重新刷新GUID,以及清空文件,方便下一次处理
  RefreshExcel();
  }
  else {
  showToast("上传的Excel文件检查不通过。请根据页面右上角的Excel模板格式进行数据录入。", "error");
  }
  }
  });
 }
 else {
  showTips(&#39;上传失败&#39;);
 }
 });
 }
Copy after login

The above logic is specifically to set the background page for uploading files to:/FileUpload/Upload, as well as the configuration parameters of various plug-ins. UploadExtraData sets additional parameters for submission, which is received by the background controller. Parameters, among which the

.on(&#39;fileuploaded&#39;, function (event, data, previewId, index) {
Copy after login

function handles the processing function after the file is uploaded. If the result returned by the uploaded file is successful, then we call ajax again to check whether the Excel field meets the requirements, as shown below:

url: &#39;/TestUser/CheckExcelColumns?guid=&#39; + guid,
Copy after login

If the background of this check returns a successful record, then you need to extract the Excel record again to preview, and clear the bootstrap fileinput file upload plug-in to facilitate the next file upload. As shown in the following code.

 if (data.Success) {
 InitImport(guid); //重新刷新表格数据
 showToast("文件已上传,数据加载完毕!");
 //重新刷新GUID,以及清空文件,方便下一次处理
 RefreshExcel();
 }
 else {
 showToast("上传的Excel文件检查不通过。请根据页面右上角的Excel模板格式进行数据录入。", "error");
 }
Copy after login

Among them, RefreshExcel is to re-update the uploaded additional parameter values ​​to facilitate the next upload. Otherwise, the values ​​of the additional parameters will not change, which will cause the GUID we set to not change and problems will occur.

 //重新更新GUID的值,并清空文件
 function RefreshExcel() {
 $("#AttachGUID").val(newGuid());
 $(&#39;#excelFile&#39;).fileinput(&#39;clear&#39;);//清空所有文件
 //附加参数初始化后一直不会变化,如果需要发生变化,则需要使用refresh进行更新
 $(&#39;#excelFile&#39;).fileinput(&#39;refresh&#39;, {
 uploadExtraData: { folder: &#39;数据导入文件&#39;, guid: $("#AttachGUID").val() },
 });
 }
Copy after login

Among them, InitImport obtains preview data and displays it on the Bootstrap-table table plug-in. For detailed use of this plug-in, you can review the essay "Experience Summary of Bootstrap Development Framework Based on Metronic (16)-- Use the plug-in bootstrap-table to implement query, paging, sorting and other processing of table records" to learn more.

 //根据条件查询并绑定结果
 var $import;
 function InitImport(guid) {
 var url = "/TestUser/GetExcelData?guid=" + guid;
 $import = $(&#39;#gridImport&#39;).bootstrapTable({
 url: url,  //请求后台的URL(*)
 method: &#39;GET&#39;,  //请求方式(*)
 striped: true,  //是否显示行间隔色
 cache: false,  //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
 pagination: false,  //是否显示分页(*)
 sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*)
 pageNumber: 1,  //初始化加载第一页,默认第一页,并记录
 pageSize: 100,  //每页的记录行数(*)
 pageList: [10, 25, 50, 100], //可供选择的每页的行数(*)
 search: false,  //是否显示表格搜索
 strictSearch: true,
 showColumns: true,  //是否显示所有的列(选择显示的列)
 showRefresh: true,  //是否显示刷新按钮
 minimumCountColumns: 2, //最少允许的列数
 clickToSelect: true, //是否启用点击选中行
 uniqueId: "ID",  //每一行的唯一标识,一般为主键列
 queryParams: function (params) { },
 columns: [{
  checkbox: true,
  visible: true  //是否显示复选框 
 }, {
  field: &#39;Name&#39;,
  title: &#39;姓名&#39;
 }, {
  field: &#39;Mobile&#39;,
  title: &#39;手机&#39;
 }, {
  field: &#39;Email&#39;,
  title: &#39;邮箱&#39;,
  formatter: emailFormatter
 }, {
  field: &#39;Homepage&#39;,
  title: &#39;主页&#39;,
  formatter: linkFormatter
 }, {
  field: &#39;Hobby&#39;,
  title: &#39;兴趣爱好&#39;
 }, {
  field: &#39;Gender&#39;,
  title: &#39;性别&#39;,
  formatter: sexFormatter
 }, {
  field: &#39;Age&#39;,
  title: &#39;年龄&#39;
 }, {
  field: &#39;BirthDate&#39;,
  title: &#39;出生日期&#39;,
  formatter: dateFormatter
 }, {
  field: &#39;Height&#39;,
  title: &#39;身高&#39;
 }, {
  field: &#39;Note&#39;,
  title: &#39;备注&#39;
 }],
 onLoadSuccess: function () {
 },
 onLoadError: function () {
  showTips("数据加载失败!");
 },
 });
 }
Copy after login

Finally, after confirming the submission, the data will be submitted to the background for processing through JS, as shown in the following code.

 //保存导入的数据
 function SaveImport() {
 var list = [];//构造集合对象
 var rows = $import.bootstrapTable(&#39;getSelections&#39;);
 for (var i = 0; i < rows.length; i++) {
 list.push({
  &#39;Name&#39;: rows[i].Name, &#39;Mobile&#39;: rows[i].Mobile, &#39;Email&#39;: rows[i].Email, &#39;Homepage&#39;: rows[i].Homepage,
  &#39;Hobby&#39;: rows[i].Hobby, &#39;Gender&#39;: rows[i].Gender, &#39;Age&#39;: rows[i].Age, &#39;BirthDate&#39;: rows[i].BirthDate,
  &#39;Height&#39;: rows[i].Height, &#39;Note&#39;: rows[i].Note
 });
 }
 if (list.length == 0) {
 showToast("请选择一条记录", "warning");
 return;
 }
 var postData = { &#39;list&#39;: list };//可以增加其他参数,如{ &#39;list&#39;: list, &#39;Rucanghao&#39;: $("#Rucanghao").val() };
 postData = JSON.stringify(postData);
 $.ajax({
 url: &#39;/TestUser/SaveExcelData&#39;,
 type: &#39;post&#39;,
 dataType: &#39;json&#39;,
 contentType: &#39;application/json;charset=utf-8&#39;,
 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
 });
 }
Copy after login

3. Background controller code analysis

Our JS code here involves several MVC background method processing: Upload, CheckExcelColumns, GetExcelData, SaveExcelData . They are introduced separately here.

The background controller method for file upload is as follows.

 /// <summary>
 /// 上传附件到服务器上
 /// </summary>
 /// <param name="fileData">附件信息</param>
 /// <param name="guid">附件组GUID</param>
 /// <param name="folder">指定的上传目录</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);
 }
Copy after login

After the file is uploaded and processed, a general CommonResult result object is returned, which is also convenient for us to judge and process on the JS client.

The process of checking whether the data we import into Excel meets the column requirements is to determine whether its data columns are consistent with our pre-set column names.

 //导入或导出的字段列表 
 string columnString = "姓名,手机,邮箱,主页,兴趣爱好,性别,年龄,出生日期,身高,备注";
 /// <summary>
 /// 检查Excel文件的字段是否包含了必须的字段
 /// </summary>
 /// <param name="guid">附件的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);
 }
Copy after login

GetExcelData formats Excel data into a specific List collection, so that we can easily operate various attributes on the client. Its code is as follows.​

 /// <summary>
 /// 获取服务器上的Excel文件,并把它转换为实体列表返回给客户端
 /// </summary>
 /// <param name="guid">附件的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);
 }
Copy after login

Another function of SaveExcelData is the final processing function for processing data import. It mainly writes the collection into a specific database. The specific code is as follows.​

 /// <summary>
 /// 保存客户端上传的相关数据列表
 /// </summary>
 /// <param name="list">数据列表</param>
 /// <returns></returns>
 public ActionResult SaveExcelData(List<TestUserInfo> list)
 {
 CommonResult result = new CommonResult();
 if (list != null && list.Count > 0)
 {
 #region 采用事务进行数据提交
 DbTransaction trans = BLLFactory<TestUser>.Instance.CreateTransaction();
 if (trans != null)
 {
  try
  {
  //int seq = 1;
  foreach (TestUserInfo detail in list)
  {
  //detail.Seq = seq++;//增加1
  detail.CreateTime = DateTime.Now;
  detail.Creator = CurrentUser.ID.ToString();
  detail.Editor = CurrentUser.ID.ToString();
  detail.EditTime = DateTime.Now;
  BLLFactory<TestUser>.Instance.Insert(detail, trans);
  }
  trans.Commit();
  result.Success = true;
  }
  catch (Exception ex)
  {
  LogTextHelper.Error(ex);
  result.ErrorMessage = ex.Message;
  trans.Rollback();
  }
 }
 #endregion
 }
 else
 {
 result.ErrorMessage = "导入信息不能为空";
 }
 return ToJsonContent(result);
 }
Copy after login

上面这几个函数的代码一般是比较有规律的,不需要一个个去编写,一般通过代码生成工具Database2Sharp批量生成即可。这样可以有效提高Web的界面代码和后台代码的开发效率,减少出错的机会。

整个导入Excel数据的处理过程,所有代码都贴出来了,基本上整个逻辑了解了就可以很好的了解这个过程的代码了。

The above is the detailed content of The BootStrap Fileinput plug-in and the table plug-in are combined to realize the steps of file upload, preview and submission of imported Excel data.. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template