In many system modules, we may need to perform certain data exchange processing, that is, data import or export operations. Such batch processing can give system users a better operating experience and improve the efficiency of users entering data. Based on the Bootstrap framework, this module is updated and viewed for Office documents or pictures.
1. Data import operation
Generally, there are data import and export operations in system modules. Therefore, when the interface is automatically generated, I tend to automatically generate these standard query, import, export and other operation functions for users. The interface effect is as follows.
In the Bootstrap framework, I put it as a layer and placed it in the index.cshtml file, which can make the entire interface more closely processed. The sample code is shown below.
In general, the following codes are automatically generated, including all the fields required. We generally tailor fields as needed to suit our business and actual needs.
<!--Import data operation layer-><div id="import" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div> <div> <div> <button type="button" data-dismiss="modal" aria-hidden="true"></button> <h4>File import</h4> </div> <div> <div> <div style="text-align:right;padding:5px"> <a href="~/Content/Template/User-Template.xls" onclick="javascript:Preview();"> <img src="~/Content/images/ico_excel.png" /> <span style="font-size:larger;font-weight:200;color:red">User-template.xls</span> </a> </div> <hr/> <form id="ffImport" method="post"> <div style="padding: 5px" data-options="iconCls:'icon-key'"> <input type="hidden" id="AttachGUID" name="AttachGUID" /> <input id="file_upload" name="file_upload" type="file" multiple="multiple"> <a href="javascript:;" id="btnUpload" onclick="javascript: $('#file_upload').uploadify('upload', '*')">Upload</a> <a href="javascript:;" id="btnCancelUpload" onclick="javascript: $('#file_upload').uploadify('cancel', '*')">Cancel</a> <div id="fileQueue"></div> <br /> <hr /> <div id="div_files"></div> <br /> </div> </form> <!--Data display table--> <table id="gridImport" cellpadding="0" cellpacing="0"> <thead id="gridImport_head"> <tr> <th><input type="checkbox" onclick="selectAll(this)"></th> <th>User encoding</th> <th>User name/login name</th> <th>Real name</th> <th>Position title</th> <th>Mobile phone</th> <th>Office phone</th> <th>Email address</th> <th>Gender</th> <th>QQ number</th> <th>Remarks</th> </tr> </thead> <tbody id="gridImport_body"></tbody> </table> </div> <div> <button type="button" data-dismiss="modal">Close</button> <button type="button" onclick="SaveImport()">Save</button> </div> </div> </div> </div> </div> </div>If we want to display the import operation interface, we only need to display this layer, as shown in the following script.
//Show the import interface function ShowImport() { $("#import").modal("show"); }The file upload processing here is mainly processed using the Uploadify control. Of course, you can also use the File Input upload control I introduced earlier for processing, which can achieve these import operations well.
In general, the initialization code of the Uploadify control is as follows
$(function () { //Add the attachment management of the interface $('#file_upload').uploadify({ 'swf': '/Content/JQueryTools/uploadify/uploadify.swf', //FLash file path'buttonText': 'brows', //Button text'uploader': '/FileUpload/Upload', //Processing uploaded page'queueID': 'fileQueue', //Queue ID 'queueSizeLimit': 1, //The maximum number of files that can be uploaded in the queue is 999 'auto': false, //Whether the file is automatically uploaded after selecting the file, the default is true 'multi': false, //Is it multiple selection, default to true 'removeCompleted': true, //Whether to remove the sequence after completion, default to true 'fileSizeLimit': '10MB', //Single file size, 0 is unlimited, can accept string values in KB, MB, GB and other units 'fileTypeDesc': 'Excel Files', //File description'fileTypeExts': '*.xls', //Uploaded file suffix filter'onQueueComplete': function (event, data) { //Event after all queues are completed//Business processing code//Prompt the user whether the Excel format is normal, if the data is loaded normally}, 'onUploadStart': function (file) { InitUpFile();//Before uploading the file, reset the GUID, and each time it is different ("#file_upload").uploadify("settings", 'formData', { 'folder': 'data import file', 'guid': $("#AttachGUID").val() }); //Dynamic parameter transfer}, 'onUploadError': function (event, queueId, fileObj, errorObj) { //alert(errorObj.type + ":" + errorObj.info); } }); });The key logic is:
//Business processing code
Generally speaking, we have obtained an Excel file in the server here, so the format of this file needs to be processed. If the format is correct, then we display the data for importing users to choose records and decide which records to import.
The code that handles checking Excel data format is as follows.
// Prompt the user whether the Excel format is normal. If the data is loaded normally, $.ajax({ url: '/User/CheckExcelColumns?guid=' + guid, type: 'get', dataType: 'json', success: function (data) { if (data.Success) { InitGrid(); //Refresh the table data showToast("The file has been uploaded, the data has been loaded!"); } else { showToast("The uploaded Excel file check fails. Please enter data according to the Excel template format in the upper right corner of the page.", "error"); } } });We add a CheckExcelColumns method in the background to check the field format of Excel files. Only files that meet the format requirements will be retrieved and displayed on the interface.
The JS code displayed on the interface is to extract the content of the Excel file and bind it to the Table element.
//Query and bind the result according to the condition function InitGrid() { var guid = $("#AttachGUID").val(); var url = "/User/GetExcelData?guid=" + guid; $.getJSON(url, function (data) { $("#gridImport_body").html(""); $.each(data.rows, function (i, item) { var tr = "<tr>"; tr += "<td><input class='checkboxes' type=/"checkbox/" name=/"checkbox/" ></td>"; tr += "<td>" + item.HandNo + "</td>"; tr += "<td>" + item.Name + "</td>"; tr += "<td>" + item.FullName + "</td>"; tr += "<td>" + item.Title + "</td>"; tr += "<td>" + item.MobilePhone + "</td>"; tr += "<td>" + item.OfficePhone + "</td>"; tr += "<td>" + item.Email + "</td>"; tr += "<td>" + item.Gender + "</td>"; tr += "<td>" + item.QQ + "</td>"; tr += "<td>" + item.Note + "</td>"; tr += "</tr>"; $("#gridImport_body").append(tr); }); }); }In order to further obtain the user imports to the specific department, we can also pop up a dialog box and select specific information, and finally submit the data to the background for processing.
The operation code is shown below.
//Save the imported data function SaveImport() { //Assign to the object $("#Company_ID3").select2("val", @Session["Company_ID"]).trigger('change'); $("#Dept_ID3").select2("val", @Session["Dept_ID"]).trigger('change'); $("#selectDept").modal("show"); }In this way, when we confirm saving, we only need to submit the data to the background through Ajax. The specific JS code is as follows.
$.ajax({ url: '/User/SaveExcelData', type: 'post', dataType: 'json', contentType: 'application/json;charset=utf-8', traditional: true, success: function (data) { if (data.Success) { //Saves successfully 1. Close the pop-up layer, 2. Clear the record display 3. Refresh the main list showToast("Saves successfully"); $("#import").modal("hide"); $(bodyTag).html(""); Refresh(); } else { showToast("Save failed:" + data.ErrorMessage, "error"); } }, data: postData });2. Data export operation
The data export operation is relatively simple. Generally speaking, we write the data into a fixed Excel table and then provide the URL to the user to download.
//Export Excel data function ShowExport() { var url = "/User/Export"; var condition = $("#ffSearch").serialize();//Get the condition executeExport(url, condition);//Execute the export}The specific logic code is as follows
//Execute the export operation and output the file function executeExport(url, condition) { $.ajax({ type: "POST", url: url, data: condition, success: function (filePath) { var downUrl = '/FileUpload/DownloadFile?file=' + filePath; window.location = downUrl; } });}3. Viewing and processing of attachments
In most cases, we may need to view the uploaded files, including Office documents, pictures, etc., which can be previewed. It is not possible. You can provide downloads and open locally to view them.
The previous file introduced that there are two ways to preview Office. One is to use the preview address of Microsoft Office for preview, and the other is to use controls to generate HTML for preview. The two can be used in combination and configure as needed.
/// <summary> /// Get the corresponding view URL according to the attachment ID. /// General rules: If it is an image file, return the view URL address '/FileUpload/ViewAttach'; /// If it is an Office file (word, PPT, Excel), etc., you can view it through Microsoft's online viewing address: 'http://view.officeapps.live.com/op/view.aspx?src=', /// You can also generate HTML files locally. If it is another file, you can download the address directly. /// </summary> /// <param name="id">Attach ID</param> /// <returns></returns> public ActionResult GetAttachViewUrl(string id) { string viewUrl = ""; FileUploadInfo info = BLLFactory<FileUpload>.Instance.FindByID(id); if (info != null) { string ext = info.FileExtend.Trim('.').ToLower(); string filePath = GetFilePath(info); bool officeInternetView = false;//Whether to use the Internet to preview string hostName = HttpUtility.UrlPathEncode("http://www.iqidi.com/");//You can configure it if (ext == "xls" || ext == "xlsx" || ext == "doc" || ext == "docx" || ext == "pptx") { if (officeInternetView) { //Return a Microsoft address to browse Office online, you need to add an Internet domain name or public IP address viewUrl = string.Format("http://view.officeapps.live.com/op/view.aspx?src={0}{1}", hostName, filePath); } else { #region Dynamically generates file for the first time //Check whether the local Office file exists. If it does not exist, create a file, and then return the path for viewing string webPath = string.Format("/GenerateFiles/Office/{0}.htm", info.ID); string generateFilePath = Server.MapPath(webPath); if (!FileUtil.FileIsExist(generateFilePath)) { string templateFile = BLLFactory<FileUpload>.Instance.GetFilePath(info); templateFile = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, templateFile.Replace("//", "/")); if (ext == "doc" || ext == "docx") { Aspose.Words.Document doc = new Aspose.Words.Document(templateFile); doc.Save(generateFilePath, Aspose.Words.SaveFormat.Html); } else if (ext == "xls" || ext == "xlsx") { Workbook workbook = new Workbook(templateFile); workbook.Save(generateFilePath, SaveFormat.Html); } else if (ext == "ppt" || ext == "pptx") { templateFile = templateFile.Replace("/", "//"); PresentationEx pres = new PresentationEx(templateFile); pres.Save(generateFilePath, Aspose.Slides.Export.SaveFormat.Html); } } #endregion viewUrl = webPath; } } else { viewUrl = filePath; } } return Content(viewUrl); }Through this background processing code, we can correctly know which URL is used when Office previewing.
In this way, on the front-end page, we only need to determine which file it is and then display it.
if(type =="image") { var imgContent = '<img src="'+ viewUrl + '" />'; $("#divViewFile").html(imgContent); $("#file").modal("show"); } else { $.ajax({ type: 'GET', url: viewUrl, //async: false, //sync//sync//dataType: 'json', success: function (json) { $("#divViewFile").html(json); $("#file").modal("show"); }, error: function (xhr, status, error) { showError("Operation failed" + xhr.responseText); //xhr.responseText } }); }The code in it
$("#file").modal("show");We call the global dialog box to display the specific content, the effect is as follows.
The word document preview effect is as follows:
Or when we view the image file, we can get the interface effect as follows:
The above is the relevant content of the BootStrap Metronic development framework experience summary [7] data import, export and accessory viewing and processing. I hope it will be helpful to everyone. If you want to know more information, please pay attention to the Wulin.com website. Here, the editor would like to thank you for your support for the Wulin.com website!