BootStrap Fileinput 플러그 인과 Bootstrap table 표 플러그 인 을 결합 하여 파일 업로드,미리 보기,제출 한 Excel 데이터 가 져 오기 작업 절 차 를 실현 합 니 다.
bootstrap-fileinput 온라인 API:http://plugins.krajee.com/file-input
boottstrap-fileinput 데모 전시:http://plugins.krajee.com/file-basic-usage-demo
이 플러그 인 은 주로 그림 업로드 처리 방법 을 소개 합 니 다.원래 제 Excel 가 져 오기 동작 은 Uploadify 플러그 인 을 사 용 했 습 니 다.제 수필 인첨부 파일 업로드 구성 요소 uploadify 사용을 참고 할 수 있 습 니 다.그러나 이것 은 Flash 컨트롤 지원 이 필요 합 니 다.일부 브 라 우 저(예 를 들 어 Chrome)에 서 는 짜증 이 나 서 일반적인 업로드 플러그 인 을 사용 하기 로 결 정 했 습 니 다.이번 에는 먼저 Bootstrap 전단 구 조 를 바탕 으로 하 는 프레임 워 크 시스템 을 업그레이드 하여 원래 의 Uploadify 플러그 인 을 대체 하면 페이지 업로드 기능 이 각 브 라 우 저 에서 차이 없 이 실 현 될 수 있 습 니 다.
일반적인 상황 에서 우 리 는 다음 두 개의 파일 을 도입 해 야 플러그 인 을 정상적으로 사용 할 수 있 습 니 다.
bootstrap-fileinput/css/fileinput.min.css
bootstrap-fileinput/js/fileinput.min.js
 //   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");
<input id="excelFile" type="file"> 
 지정 한 파일 을 선택 하면 엑셀 의 파일 목록 을 볼 수 있 습 니 다.다음 화면 에서 보 여 줍 니 다.
 
 파일 을 업로드 한 후 데 이 터 는 팝 업 층 의 목록 에 직접 전 시 됩 니 다.여 기 는 Bootstrap-table 표 플러그 인 을 직접 사용 하여 보 여 줍 니 다.
 
 이렇게 하면 우 리 는 엑셀 의 기록 을 보 여 주 며 미리 보기 기능 을 실현 하고 필요 한 기록 을 선택 한 다음 에 저장 하면 서버 에 제출 하여 저장 할 수 있 으 며 엑셀 데이터 의 진정한 가 져 오기 데이터베이스 처 리 를 실현 할 수 있다.
2.엑셀 내 보 내기 작업 에 대한 상세 한 설명
우 리 는 실제 엑셀 을 가 져 오 는 인터페이스 에서 HTML 코드 는 다음 과 같다.
<!--       -->
<div id="import" class="modal fade bs-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
 <div class="modal-dialog modal-lg">
 <div class="modal-content">
 <div class="modal-header bg-primary">
 <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
 <h4 class="modal-title">    </h4>
 </div>
 <div class="modal-body">
 <div style="text-align:right;padding:5px">
  <a href="~/Content/Template/TestUser-  .xls" rel="external nofollow" onclick="javascript:Preview();">
  <img alt="      -  " src="~/Content/images/ico_excel.png" />
  <span style="font-size:larger;font-weight:200;color:red">TestUser-  .xls</span>
  </a>
 </div>
 <hr/>
 <form id="ffImport" method="post">
  <div title="Excel    " style="padding: 5px">
  <input type="hidden" id="AttachGUID" name="AttachGUID" /> 
  <input id="excelFile" type="file"> 
  </div>
 </form>
 <!--      -->
 <table id="gridImport" class="table table-striped table-bordered table-hover" cellpadding="0" cellspacing="0" border="0">
 </table>
 </div>
 <div class="modal-footer">
 <button type="button" class="btn btn-default" data-dismiss="modal">  </button>
 <button type="button" class="btn btn-primary" onclick="SaveImport()">  </button>
 </div>
 </div>
 </div>
</div>
 //   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: '<i class="glyphicon glyphicon-file"></i>',
 allowedPreviewTypes: null,
 previewFileIconSettings: {
  'docx': '<i class="glyphicon glyphicon-file"></i>',
  'xlsx': '<i class="glyphicon glyphicon-file"></i>',
  'pptx': '<i class="glyphicon glyphicon-file"></i>',
  'jpg': '<i class="glyphicon glyphicon-picture"></i>',
  'pdf': '<i class="glyphicon glyphicon-file"></i>',
  'zip': '<i class="glyphicon glyphicon-file"></i>',
 },
 uploadExtraData: { //     ,       
  folder: '      ', guid: $("#AttachGUID").val()
 }
 }) //          
 .on('fileuploaded', 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('    ');
  var guid = $("#AttachGUID").val();
  //    Excel      ,        
  $.ajax({
  url: '/TestUser/CheckExcelColumns?guid=' + guid,
  type: 'get',
  dataType: 'json',
  success: function (data) {
  if (data.Success) {
  InitImport(guid); //        
  showToast("     ,      !");
  //    GUID,      ,       
  RefreshExcel();
  }
  else {
  showToast("   Excel       。         Excel          。", "error");
  }
  }
  });
 }
 else {
  showTips('    ');
 }
 });
 }
.on('fileuploaded', function (event, data, previewId, index) {
url: '/TestUser/CheckExcelColumns?guid=' + guid,
 if (data.Success) {
 InitImport(guid); //        
 showToast("     ,      !");
 //    GUID,      ,       
 RefreshExcel();
 }
 else {
 showToast("   Excel       。         Excel          。", "error");
 }
 //    GUID  ,     
 function RefreshExcel() {
 $("#AttachGUID").val(newGuid());
 $('#excelFile').fileinput('clear');//      
 //              ,        ,     refresh    
 $('#excelFile').fileinput('refresh', {
 uploadExtraData: { folder: '      ', guid: $("#AttachGUID").val() },
 });
 }
 //           
 var $import;
 function InitImport(guid) {
 var url = "/TestUser/GetExcelData?guid=" + guid;
 $import = $('#gridImport').bootstrapTable({
 url: url,  //     URL(*)
 method: 'GET',  //    (*)
 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: 'Name',
  title: '  '
 }, {
  field: 'Mobile',
  title: '  '
 }, {
  field: 'Email',
  title: '  ',
  formatter: emailFormatter
 }, {
  field: 'Homepage',
  title: '  ',
  formatter: linkFormatter
 }, {
  field: 'Hobby',
  title: '    '
 }, {
  field: 'Gender',
  title: '  ',
  formatter: sexFormatter
 }, {
  field: 'Age',
  title: '  '
 }, {
  field: 'BirthDate',
  title: '    ',
  formatter: dateFormatter
 }, {
  field: 'Height',
  title: '  '
 }, {
  field: 'Note',
  title: '  '
 }],
 onLoadSuccess: function () {
 },
 onLoadError: function () {
  showTips("      !");
 },
 });
 }
 //       
 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
 });
 }여기 서 우리 의 JS 코드 에는 몇 가지 MVC 배경 방법 처리 가 포함 되 어 있 습 니 다.Upload,CheckExcelColumns,GetExcelData,SaveExcelData.여기 서 따로 소개 하 겠 습 니 다.
파일 업로드 배경 컨트롤 러 방법 은 다음 과 같 습 니 다.
 /// <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);
 }그 중에서 저희 가 엑셀 을 가 져 온 데이터 가 열 요 구 를 만족 시 키 는 지 확인 하 는 것 은 데이터 열 이 저희 가 미리 설정 한 열 이름과 일치 하 는 지 판단 하 는 것 입 니 다.
 //           
 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);
 }
 /// <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);
 }
 /// <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);
 }Excel 데 이 터 를 가 져 오 는 전체 처리 과정 에서 모든 코드 가 붙 어 있 습 니 다.기본적으로 전체 논 리 를 이해 하면 이 과정의 코드 를 잘 이해 할 수 있 습 니 다.
총결산
위 에서 설명 한 것 은 여러분 에 게 소 개 된 BootStrap Fileinput 플러그 인과 Bootstrap table 표 플러그 인 을 결합 하여 파일 업로드,미리 보기,제출 한 Excel 데이터 가 져 오기 작업 절 차 를 실현 하 는 것 입 니 다.여러분 에 게 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 메 시 지 를 남 겨 주세요.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
부트스트랩 5 스티커Sticky는 페이지의 특정 영역에서 요소를 잠글 수 있도록 하는 구성 요소입니다. 수동 설치(zip 패키지) 부트스트랩 이미지 구성 요소를 활용하고 프로젝트에서 사용하려면 먼저 을 설치해야 합니다. MDB CLI ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.