Summary of BootStrap Metronic Development Framework experience [7] data import and export and viewing of attachments, bootstrapmetronic

Source: Internet
Author: User
Tags microsoft address

Summary of BootStrap Metronic Development Framework experience [7] data import and export and viewing of attachments, bootstrapmetronic

In many system modules, we may need to exchange data, that is, import or export data. Such batch processing can provide a better user experience, it also improves the efficiency of user data input. Based on the Bootstrap framework, this article updates this module and displays Office documents, images, and other attachments.

1. Import Data

Generally, system modules have data import and export operations. 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.

Import operations. In the Bootstrap framework, I use it as a layer and place it in the index. in the cshtml file, the processing of the entire interface can be closer. The sample code is as follows.

The following code is generally automatically generated, including all required fields. We usually crop fields as needed to meet our business and actual needs.

<! -- Import data operation layer --> <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> 

To display the import operation interface, you only need to display this layer, as shown in the following script.

// Display the import interface function ShowImport () {$ ("# import"). modal ("show ");}

The File upload process here mainly uses the Uploadify Control for processing. Of course, you can also use the File Input upload control I introduced earlier to process it, these import operations can be well implemented.

The initialization code of the Uploadify control is as follows:

$ (Function () {// Add an attachment to the interface $ ('# file_upload '). uploadify ({'swf ':'/Content/JQueryTools/uploadify/uploadify.swf ', // path of the FLash file 'buttontext': 'browsed', // button text 'upload ': '/FileUpload/upload', // the Upload processing page 'queueid': 'filequee', // queue ID 'queuesizelimit': 1, // The maximum number of files that can be uploaded in the queue. The default value is 999 'auto': false. // if the file is automatically uploaded after the queue is selected, the default value is true 'multi ': false, // whether multiple objects are selected. The default value is true 'removecompleted': true, // whether to remove the sequence after completion. The default value is true 'filesizelimmit ': '10mb', // the size of a single object, 0 is unrestricted. Acceptable string values in units such as KB, MB, and GB are 'filetypedesc': 'excel Files ', // file description 'filetypeexists ':'*. xls ', // the filename suffix filter 'onqueuecomplete': function (event, data) {// events 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 (); // reset the GUID before the file is uploaded. Each time it is different $ ("# file_upload "). uploadify ("settings", 'formdata', {'folder': 'Data import file', 'guid': $ ("# AttachGUID "). val ()}); // dynamically passing parameters}, 'onuploaderror': function (event, queueId, fileObj, errorObj) {// alert (errorObj. type + ":" + errorObj.info );}});});

The key logic is:

// Business processing code

Generally, we have obtained an Excel file from the server. Therefore, we need to process the file format. If the format is correct, we will display the data, for the import user to select the records and decide to import those records.

The code for processing and checking the Excel data format is as follows.

// Prompt whether the Excel format is normal. If the data is loaded normally $. ajax ({url: '/User/CheckExcelColumns? Guid = '+ guid, type: 'get', ype: 'json', success: function (data) {if (data. success) {InitGrid (); // refresh table data showToast ("File Uploaded, data loaded! ");} Else {showToast (" the uploaded Excel file fails to be checked. Enter data according to the Excel template format in the upper-right corner of the page. "," Error ");}}});

We just added a CheckExcelColumns method in the background to check the Field Format of the Excel file. Only files that meet the format requirements will be obtained and displayed on the interface.

The JS Code displayed on the interface, that is, the content of the Excel file is extracted and bound to the Table element.

// Query and bind the result 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 );});});}

To further obtain the information imported from the user to a specific department, a dialog box is displayed, and the specific information is selected before the data is submitted to the background for processing.

The operation code is as follows.

// Save the imported data function SaveImport () {// assign a value 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, you only need to use Ajax to submit the data to the background for processing. 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) {// saved successfully. close the pop-up layer, 2. clear record display 3. refresh the master list showToast ("saved successfully"); $ ("# import "). modal ("hide"); iterator (bodytag).html (""); Refresh ();} else {showToast ("failed to save:" + data. errorMessage, "error") ;}, data: postData });

2. Export data

The data export operation is relatively simple. Generally, we write the data into a fixed Excel table and provide the URL for users to download.

// Export Excel Data function ShowExport () {var url = "/User/Export"; var condition = $ ("# ffSearch "). serialize (); // obtain the condition executeExport (url, condition); // execute export}

The specific logic code is as follows:

// Execute the export operation. The output 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. view attachments

In most cases, you may need to view the uploaded files, including Office documents and images, and preview them.

In the previous article, we introduced two ways to preview the Office. One is to preview the Microsoft Office preview address, the other is to generate HTML with controls for preview, and the other two can be used in combination, configure as needed.

/// <Summary> /// obtain the view URL Based on the attachment ID. /// If the general rule is an image file, return the view URL '/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 an HTML file locally. For other files, you can directly. /// </Summary> /// <param name = "id"> attachment 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 Internet Online Preview string hostName = HttpUtility. urlPathEncode ("http://www.iqidi.com/"); // you can configure it, if necessary, if (ext = "xls" | ext = "xlsx" | ext = "doc" | ext = "docx" | ext =" ppt "| ext =" pptx ") {if (officeInternetView) {// return a Microsoft address for online Office browsing. You need to add the Internet domain name or public IP address viewU. Rl = string. Format ("http://view.officeapps.live.com/op/view.aspx? Src = {0} {1} ", hostName, filePath);} else {# region dynamically generates a file for the first time. // check whether the local Office file exists. If it does not exist, convert it into a file, then return the path for viewing string webPath = string. format ("/GenerateFiles/Office/program 02.16.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 during Office preview.

In this way, on the front-end page, we only need to determine the specific file and then display it.

If (type = "image") {var imgContent = ''; $ ("# divViewFile" ).html (imgContent ); $ ("# file "). modal ("show");} else {$. ajax ({type: 'get', url: viewUrl, // async: false, // synchronous // dataType: 'json', success: function (json) {$ ("# divViewFile" ).html (json); $ ("# file "). modal ("show") ;}, error: function (xhr, status, error) {showError ("operation failed" + xhr. responseText); // xhr. responseText }});}

Code

$("#file").modal("show");

The global dialog box is called to display the specific content. The effect is as follows.

The Word document preview effect is as follows:

You can also view the image file as follows:

The above is a summary of the BootStrap Metronic Development Framework experience [7] data import, export, and attachment viewing and processing. I hope to help you, if you want to learn more, please stay tuned to the help House website. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.